library(splines)
library(textables)


myp<-function(z){
  if(pnorm(z) > 0.025) z2 <- 1
  else z2 <- 0.051
    return(z2)
}

integer_breaks <- function(n = 5, ...) {
  fxn <- function(x) {
    breaks <- floor(pretty(x, n, ...))
    names(breaks) <- attr(breaks, "labels")
    breaks
  }
  return(fxn)
}

simse<-function(x){
  return(((1+1/numS)*(x)^2)^0.5)
}

sigstar <- function(b,se){
  
  output <- round(b,3)
  output[which(abs(b/simse(se))>1.96)]<-paste0(output[which(abs(b/simse(se))>1.96)],"$^*$")
  return(output)
}
cost<-function(param,uflow){
  meanC<- uflow
  as.character(paste0("\\$",round(meanC/exp(param) - meanC)))
}

evalfit<-function(simdata,path,suffix,shocks.wagenoise, shocks.spwagenoise, onlysingle=FALSE,onlymarried=FALSE,onlyFT=FALSE,nocomp=FALSE,noflow=FALSE,nohealthyDI=FALSE, noeventDI=TRUE,
                  nocontflow=TRUE, nostockDI=FALSE,
                  nowagemoments=FALSE,
                  nospmoments=FALSE, noworkDImoments=TRUE,consmoments_simple=TRUE,
                  workmoments_simple=TRUE,
                  DImoments_simple=TRUE){
  output<-copy(simdata)
  output[,married:=single==0]
  #####STANDARD ERRORS:
  output<-output[order(Type,i,time),]
  output[,married:=single==0]
  output[,Workpart_single:=Workpart==1&single==1]
  output[,Workpart_married:=Workpart==1&single==0]
  output[,Work_single:=Work==1&single==1]
  output[,Work_married:=Work==1&single==0]
  output[,yearDI_H1:=yearDI==1&Health==1]
  output[,yearDI_H2:=yearDI==1&Health==2]
  output[,yearDI_H3:=yearDI==1&Health==3]
  output[single==1,spHealth:=1]
  output[,spH1:=spHealth==1]
  output[,spH2:=spHealth==2]
  
  if(onlyFT) {
    cons2moments_single<-consmoments_single #[-4]
    cons2moments_married<-consmoments_married #[-c(4,7,8,11,13)]
    cons2moments_all<-consmoments_all #[-c(4,11,14,15,18,20)]
    spworkmoments<-spworkfullmoments
    cons2se_single<-consse_single #[-4]
    cons2se_married<-consse_married #[-c(4,7,8,11,13)]
    cons2se_all<-consse_all #[-c(4,11,14,15,18,20)]
    if(workmoments_simple==TRUE){
      workmoments_married <- workfullmoments_simple
      workmoments_single <- NULL
      workse_married<-workfullse_simple
      workse_single<-NULL
    } else{
      workmoments_single<-workfullmoments_single
      workmoments_married<-workfullmoments_married
      workse_single<-workfullse_single
      workse_married<-workfullse_married
    }
    spworkse<-spworkfullse
    consnames_single<-c("$H_t^1 = 1$","$H_t^1 = 2$","$L_t^1 = 1$","$DI \\times (H_t^1 = 0)$","$DI \\times (H_t^1 = 1)$","$DI \\times (H_t^1 = 2)$", "$L_t^1 \\times \\times (H_t^1 = 1)$", "$L_t^1 \\times (H_t^1 = 2)$")
    consnames_married<-c("$H_t^1 = 1$","$H_t^1 = 2$","$L_t^1 = 1$","$DI \\times (H_t^1 = 0)$","$DI \\times (H_t^1 = 1)$","$DI \\times (H_t^1 = 2)$","$H_t^2 = 1","L_t^2 = 1$","$DI \\times (H_t^1 = 0)$","$DI \\times (H_t^1 = 1)$","$DI \\times (H_t^1 = 2)$")
    consnames_all<-c("($H_t^1 = 1) \\times (M_t = 0)$","$(H_t^1 = 2) \\times (M_t = 0)$","$(L_t^1 = 1) \\times (M_t = 0)$","$(DI_t = 1 ) \\times (H_t^1 = 0) \\times (M_t = 0)$","$(DI_t = 1 ) \\times (H_t^1 = 1) \\times (M_t = 0)$","$(DI_t = 1 ) \\times (H_t^1 = 2) \\times (M_t = 0)$",
                     "$M_t = 1$","($H_t^1 = 1) \\times (M_t = 1)$","$(H_t^1 = 2) \\times (M_t = 1)$","$(L_t^1 = 1) \\times (M_t = 1)$", "$(L_t^1 = 1) \\times (H_t^1 = 1)$", "$(L_t^1 = 1) \\times (H_t^1 = 2)$", "$H_t^2 = 1$","$L_t^2 = 1$", "$(L_t^2 = 1) \\times (H_t^2 = 1)$",
                     "$(DI_t =1) \\times (H_t^1 = 0) \\times (M_t = 1)$","$(DI_t =1) \\times (H_t^1 = 1) \\times (M_t = 1)$","$(DI_t =1) \\times (H_t^1 = 2) \\times (M_t = 1)$")
  } else{
    cons2moments_single<-consmoments_single
    cons2moments_married<-consmoments_married
    cons2moments_all<-consmoments_all
    workmoments_single<-c(workfullmoments_single,workpartmoments_single)
    workmoments_married<-c(workfullmoments_married,workpartmoments_married)
    spworkmoments<-c(spworkfullmoments,spworkpartmoments)
    cons2se_single<-consse_single
    cons2se_married<-consse_married
    cons2se_all<-consse_all
    workse_single<-c(workfullse_single,workpartse_single)
    workse_married<-c(workfullse_married,workpartse_married)
    spworkse<-c(spworkfullse,spworkpartse)
    consnames_single<-c("Disab (mod)","Disab (sev)","Head Work (FT)","Head Work (PT)","DI (healthy)","DI $\\times$ Disab (mod)","DI $\\times$ Disab (sev)", "Work (FT) $\\times$ Disab (mod)", "Work (FT) $\\times$ Disab (sev)", "Work (PT) $\\times$ Disab (mod)", "Work (PT) $\\times$ Disab (sev)")
    consnames_married<-c("Disab (mod)","Disab (sev)","Head Work (FT)","Head Work (PT)", "Work (FT) $\\times$ Disab (mod)", "Work (FT) $\\times$ Disab (sev)", "Work (PT) $\\times$ Disab (mod)", "Work (PT) $\\times$ Disab (sev)","Spouse Disab","Spouse Work (FT)","Spouse Work (PT)","DI (healthy)","DI $\\times$ Disab (mod)","DI $\\times$ Disab (sev)")
    consnames_all<-c("Disab (mod), single","Disab (sev), single","Head Work (FT), single","Head Work (PT), single","DI (healthy), single","DI $\\times$ Disab (mod), single","DI $\\times$ Disab (sev), single",
                     "Married","Disab (mod), married","Disab (sev), married","Head Work (FT), married","Head Work (PT), married", "Work (FT) $\\times$ Disab (mod)", "Work (FT) $\\times$ Disab (sev)", "Work (PT) $\\times$ Disab (mod)", "Work (PT) $\\times$ Disab (sev)", "Spouse Disab","Spouse Work (FT)","Spouse Work (PT)", "Spouse Work (FT) $\\times$ Disab", "Spouse Work (PT) $\\times$ Disab",
                     "DI (Healthy), married","DI $\\times$ Disab (mod), married","DI $\\times$ Disab (sev), married")
  }
  if(DImoments_simple==TRUE){
    stockDI_all<-stockDImoments_simple
    stockDI_error_all<-stockDIse_simple
    stockDI_mar<-stockDI_all
    stockDI_error_mar<-stockDI_error_all
    
    compDI_all<-compDImoments_simple
    compDI_error_all<-compDIse_simple
    compDI_mar<-compDI_all
    compDI_error_mar<-compDI_error_all
    compDI_sing<-NULL
    compDI_error_sing<-NULL
    
    flowDI_all<-flowDImoments_simple
    flowDI_error_all<-flowDIse_simple
    flowDI_mar<-flowDI_all
    flowDI_error_mar<-flowDI_error_all
    flowDI_sing<-NULL
    flowDI_error_sing<-NULL
    
    #contflowDI_all<-contflowDImoments_simple
    #contflowDI_error_all<-contflowDIse_simple
    #contflowDI_mar<-contflowDI_all
    #contflowDI_error_mar<-contflowDI_error_all
    #contflowDI_sing<-NULL
    #contflowDI_error_sing<-NULL
    contflowDI_all<-contflowDImoments
    contflowDI_error_all<-contflowDIse
    contflowDI_mar<-contflowDImoments_married
    contflowDI_sing<-contflowDImoments_single
    contflowDI_error_mar<-contflowDIse_married
    contflowDI_error_sing<-contflowDIse_single
    
    eventDI_all <- eventDImoments_simple
    eventDI_error_all <- eventDIse_simple
    eventDI_mar<-eventDI_all
    eventDI_error_mar<-eventDI_error_all
    eventDI_sing<-NULL
    eventDI_error_sing<-NULL
    
  } else if(nohealthyDI==TRUE){
    stockDI_all<-stockDImoments_all[!grepl("L=0",names(stockDImoments_all))]
    stockDI_error_all<-stockDIse_all[!grepl("L=0",names(stockDIse_all))]
    
    compDI_all<-compDImoments_all[!grepl("L=0",names(compDImoments_all))]
    compDI_error_all<-compDIse_all[!grepl("L=0",names(compDIse_all))]
    
    flowDI_all<-flowDImoments[!grepl("L=0",names(flowDImoments))]
    flowDI_error_all<-flowDIse[!grepl("L=0",names(flowDIse))]
    
    contflowDI_all<-contflowDImoments[!grepl("L=0",names(contflowDImoments))]
    contflowDI_error_all<-contflowDIse[!grepl("L=0",names(contflowDIse))]
    
    eventDI_all <- eventDImoments
    eventDI_error_all <- eventDIse
    stockDI_sing<-stockDImoments_single[!grepl("L=0",names(stockDImoments_single))]
    stockDI_error_sing<-stockDIse_single[!grepl("L=0",names(stockDIse_single))]
    stockDI_mar<-stockDImoments_married[!grepl("L=0",names(stockDImoments_married))]
    stockDI_error_mar<-stockDIse_married[!grepl("L=0",names(stockDIse_married))]
    
    compDI_sing<-compDImoments_single[!grepl("L=0",names(compDImoments_single))]
    compDI_error_sing<-compDIse_single[!grepl("L=0",names(compDIse_single))]
    compDI_mar<-compDImoments_married[!grepl("L=0",names(compDImoments_married))]
    compDI_error_mar<-compDIse_married[!grepl("L=0",names(compDIse_married))]

    flowDI_mar<-flowDImoments_married[!grepl("L=0",names(flowDImoments_married))]
    flowDI_sing<-flowDImoments_single[!grepl("L=0",names(flowDImoments_single))]
    flowDI_error_mar<-flowDIse_married[!grepl("L=0",names(flowDI_error_mar))]
    flowDI_error_sing<-flowDIse_single[!grepl("L=0",names(flowDI_error_sing))]

    contflowDI_mar<-contflowDImoments_married[!grepl("L=0",names(contflowDImoments_married))]
    contflowDI_sing<-contflowDImoments_single[!grepl("L=0",names(contflowDImoments_single))]
    contflowDI_error_mar<-contflowDIse_married[!grepl("L=0",names(contflowDI_error_mar))]
    contflowDI_error_sing<-contflowDIse_single[!grepl("L=0",names(contflowDI_error_sing))]
    
    eventDI_sing <- eventDImoments_single
    eventDI_error_sing <- eventDIse_single
    eventDI_mar <- eventDImoments_married
    eventDI_error_mar <- eventDIse_married
  } else{
    stockDI_sing<-stockDImoments_single
    stockDI_error_sing<-stockDIse_single
    stockDI_mar<-stockDImoments_married
    stockDI_error_mar<-stockDIse_married
    stockDI_all<-stockDImoments_all
    stockDI_error_all<-stockDIse_all
    
    compDI_sing<-compDImoments_single
    compDI_error_sing<-compDIse_single
    compDI_mar<-compDImoments_married
    compDI_error_mar<-compDIse_married
    compDI_all<-compDImoments_all
    compDI_error_all<-compDIse_all
    
    flowDI_all<-flowDImoments
    flowDI_error_all<-flowDIse
    flowDI_mar<-flowDImoments_married
    flowDI_sing<-flowDImoments_single
    flowDI_error_mar<-flowDIse_married
    flowDI_error_sing<-flowDIse_single

    contflowDI_all<-contflowDImoments
    contflowDI_error_all<-contflowDIse
    contflowDI_mar<-contflowDImoments_married
    contflowDI_sing<-contflowDImoments_single
    contflowDI_error_mar<-contflowDIse_married
    contflowDI_error_sing<-contflowDIse_single
    
    eventDI_sing <- eventDImoments_single
    eventDI_error_sing <- eventDIse_single
    eventDI_mar <- eventDImoments_married
    eventDI_error_mar <- eventDIse_married
    eventDI_all <- eventDImoments
    eventDI_error_all <- eventDIse
    
  }
  if(consmoments_simple==TRUE){
    cons2moments_single <- consmoments_simple_single
    cons2moments_married <- consmoments_simple_married
    cons2moments_all <- consmoments_simple_all
    cons2se_all <- consse_simple_all
    cons2se_single <- consse_simple_single
    cons2se_married <- consse_simple_married
    consnames_single<-c("$H_t^1$","$L_t^1$","$DI$", "$L_t^1 \\times H_t^1$")
    consnames_married<-c("$H_t^1$","$L_t^1$", "$L_t^1 \\times H_t^1$", "$H_t^2$","$L_t^2 = 1$","$L_t^2 \\times H_t^2$","$DI$")
    consnames_all<-c("$H_t^1$","$L_t^1$","$DI_t$",
                     "$L_t^1 \\times H_t$", "$H_t^2$","$L_t^2$", "$L_t^2 \\times H_t^2$")
  }
  if(nowagemoments==FALSE){
    wagereg <- wageregmoments
    spwagereg <- spwageregmoments
    wagevar <- wagevarmoments
    wagese <- wageregse
    spwagese <- spwageregse
    wagevse <- wagevarse
    
    wagenames<-c("$f_1$","$f_2$","$f_3$","$H = 2$","$H = 1$","$Age$","$Age^2/100$","$Age \\ge 45$","$H = 2 \\times Age \\ge 45$", "$H = 1 \\times Age \\ge 45$")
    spwagenames<-c("$f_1$","$f_2$","$f_3$","$H = 1$","$Age$","$Age^2/100$","$Age \\ge 45$","$H = 1 \\times Age \\ge 45$")
    wagevarnames<-c("Variance","Autocovariance","Spouse Variance","Spouse Autocovariance","Intra-Household Covariance")
    names(wagereg)<-wagenames
    names(spwagereg)<-spwagenames
    names(wagevar)<-wagevarnames
  } else{
    wagereg<-NULL
    spwagereg<-NULL
    wagevar<-NULL
  }
  
  worknames<-c("Healthy, Age $<$ 45","Healthy, Age $\\ge$ 45","Mod. Dis., Age $<$ 45", "Mod. Dis., Age $\\ge$ 45","Sev. Dis., Age $<$ 45","Sev. Dis., Age $\\ge$ 45",
               "Healthy, Age $<$ 45","Healthy, Age $\\ge$ 45","Mod. Dis., Age $<$ 45", "Mod. Dis., Age $\\ge$ 45","Sev. Dis., Age $<$ 45","Sev. Dis., Age $\\ge$ 45")
  spworknames<-c("$H_t^2 = 0, age_t < 45$","$H_t^2 = 0, age_t \\ge 45$","$H_t^2 = 1, age_t < 45$","$H_t^2 = 1, age_t \\ge 45$")
  stockDInames<-c("$H_t^1 = 0, age_t < 45$","$H_t^1 = 1, age_t < 45$","$H_t^1 = 2, age_t < 45$","$H_t^1 = 0, age_t \\ge 45$","$H_t^1 = 1, age_t \\ge 45$","$H_t^1 = 2, age_t \\ge 45$",
                  "$H_t^1 = 0, age_t < 45$","$H_t^1 = 1, age_t < 45$","$H_t^1 = 2, age_t < 45$","$H_t^1 = 0, age_t \\ge 45$","$H_t^1 = 1, age_t \\ge 45$","$H_t^1 = 2, age_t \\ge 45$")
  flowDInames <- c("Healthy, Age $<$ 45","Mod. Dis., Age $<$ 45","Sev. Dis., Age $<$ 45","Healthy, Age $\\ge$ 45","Mod. Dis., Age $\\ge$ 45","Sev. Dis., Age $\\ge$ 45",
                       "Healthy, Age $<$ 45","Mod. Dis., Age $<$ 45","Sev. Dis., Age $<$ 45","Healthy, Age $\\ge$ 45","Mod. Dis., Age $\\ge$ 45","Sev. Dis., Age $\\ge$ 45")
  contflowDInames<-c("$H_t^1 = 0, age_t < 45$","$H_t^1 = 1, age_t < 45$","$H_t^1 = 2, age_t < 45$","$H_t^1 = 0, age_t \\ge 45$","$H_t^1 = 1, age_t \\ge 45$","$H_t^1 = 2, age_t \\ge 45$",
                     "$H_t^1 = 0, age_t < 45$","$H_t^1 = 1, age_t < 45$","$H_t^1 = 2, age_t < 45$","$H_t^1 = 0, age_t \\ge 45$","$H_t^1 = 1, age_t \\ge 45$","$H_t^1 = 2, age_t \\ge 45$")
  compDInames<-c("$H_t=2,age_t < 45$","$H_t=2,age_t \\ge 45$","$H_t=1,age_t < 45$","$H_t=1,age_t \\ge 45$","$H_t=0,age_t < 45$","$H_t=0,age_t \\ge 45$",
                 "$H_t=2,age_t < 45$","$H_t=2,age_t \\ge 45$","$H_t=1,age_t < 45$","$H_t=1,age_t \\ge 45$","$H_t=0,age_t < 45$","$H_t=0,age_t \\ge 45$")
  # worknames<-c("$P(L_t^1 = 1 | H_t^1 = 0, age_t \\le 45, M_t = 1)$","$P(L_t^1 = 1 | H_t^1 = 0, age_t > 45, M_t = 1)$","$P(L_t^1 = 1 | H_t^1 = 1, age_t \\le 45, M_t = 1)$","$P(L_t^1 = 1 | H_t^1 = 1, age_t > 45, M_t = 1)$","$P(L_t^1 = 1 | H_t^1 = 2, age_t \\le 45, M_t = 1)$","$P(L_t^1 = 1 | H_t^1 = 2, age > 45, M = 1)$",
  #              "$P(L_t^1 = 1 | H_t^1 = 0, age_t \\le 45, M_t = 0)$","$P(L_t^1 = 1 | H_t^1 = 0, age_t > 45, M_t = 0)$","$P(L_t^1 = 1 | H_t^1 = 1, age_t \\le 45, M_t = 0)$","$P(L_t^1 = 1 | H_t^1 = 1, age_t > 45, M_t = 0)$","$P(L_t^1 = 1 | H_t^1 = 2, age_t \\le 45, M_t = 0)$","$P(L_t^1 = 1 | H_t^1 = 2, age > 45, M = 0)$")
  # spworknames<-c("$P(L_t^2 = 1 | H_t^2 = 0, age_t \\le 45)$","$P(L_t^2 = 1 | H_t^2 = 0, age_t > 45)$","$P(L_t^2 = 1 | H_t^2 = 1, age_t \\le 45)$","$P(L_t^2 = 1 | H_t^2 = 1, age_t > 45)$")
  # stockDInames<-c("$P(DI_t = 1 | H_t^1 = 0, age_t \\le 45, M_t = 1)$","$P(DI_t = 1 | H_t^1 = 1, age_t \\le 45, M_t = 1)$","$P(DI_t = 1 | H_t^1 = 2, age_t \\le 45, M_t = 1)$","$P(DI_t = 1 | H_t^1 = 0, age_t > 45, M_t = 1)$","$P(DI_t = 1 | H_t^1 = 1, age_t > 45, M_t = 1)$","$P(DI_t = 1 | H_t^1 = 2, age_t > 45, M_t = 1)$",
  #                 "$P(DI_t = 1 | H_t^1 = 0, age_t \\le 45, M_t = 0)$","$P(DI_t = 1 | H_t^1 = 1, age_t \\le 45, M_t = 0)$","$P(DI_t = 1 | H_t^1 = 2, age_t \\le 45, M_t = 0)$","$P(DI_t = 1 | H_t^1 = 0, age_t > 45, M_t = 0)$","$P(DI_t = 1 | H_t^1 = 1, age_t > 45, M_t = 0)$","$P(DI_t = 1 | H_t^1 = 2, age_t > 45, M_t = 0)$")
  # flowDInames<-c("$P(DI_t = 1 | DI_{t-1}=0, H_t^1 = 0, age_t \\le 45, M_t = 1)$","$P(DI_t = 1 | DI_{t-1}=0, H_t^1 = 1, age_t \\le 45, M_t = 1)$","$P(DI_t = 1 | DI_{t-1}=0, H_t^1 = 2, age_t \\le 45, M_t = 1)$","$P(DI_t = 1 | DI_{t-1}=0, H_t^1 = 0, age_t > 45, M_t = 1)$","$P(DI_t = 1 | DI_{t-1}=0, H_t^1 = 1, age_t > 45, M_t = 1)$","$P(DI_t = 1 | DI_{t-1}=0, H_t^1 = 2, age_t > 45, M_t = 1)$",
  #                "$P(DI_t = 1 | DI_{t-1}=0, H_t^1 = 0, age_t \\le 45, M_t = 0)$","$P(DI_t = 1 | DI_{t-1}=0, H_t^1 = 1, age_t \\le 45, M_t = 0)$","$P(DI_t = 1 | DI_{t-1}=0, H_t^1 = 2, age_t \\le 45, M_t = 0)$","$P(DI_t = 1 | DI_{t-1}=0, H_t^1 = 0, age_t > 45, M_t = 0)$","$P(DI_t = 1 | DI_{t-1}=0, H_t^1 = 1, age_t > 45, M_t = 0)$","$P(DI_t = 1 | DI_{t-1}=0, H_t^1 = 2, age_t > 45, M_t = 0)$")
  # contflowDInames<-c("$P(DI_t = 1 | DI_{t-1}=1, H_t^1 = 0, age_t \\le 45, M_t = 1)$","$P(DI_t = 1 | DI_{t-1}=1, H_t^1 = 1, age_t \\le 45, M_t = 1)$","$P(DI_t = 1 | DI_{t-1}=1, H_t^1 = 2, age_t \\le 45, M_t = 1)$","$P(DI_t = 1 | DI_{t-1}=1, H_t^1 = 0, age_t > 45, M_t = 1)$","$P(DI_t = 1 | DI_{t-1}=1, H_t^1 = 1, age_t > 45, M_t = 1)$","$P(DI_t = 1 | DI_{t-1}=1, H_t^1 = 2, age_t > 45, M_t = 1)$",
  #                    "$P(DI_t = 1 | DI_{t-1}=1, H_t^1 = 0, age_t \\le 45, M_t = 0)$","$P(DI_t = 1 | DI_{t-1}=1, H_t^1 = 1, age_t \\le 45, M_t = 0)$","$P(DI_t = 1 | DI_{t-1}=1, H_t^1 = 2, age_t \\le 45, M_t = 0)$","$P(DI_t = 1 | DI_{t-1}=1, H_t^1 = 0, age_t > 45, M_t = 0)$","$P(DI_t = 1 | DI_{t-1}=1, H_t^1 = 1, age_t > 45, M_t = 0)$","$P(DI_t = 1 | DI_{t-1}=1, H_t^1 = 2, age_t > 45, M_t = 0)$")
  # compDInames<-c("$P(H_t=2|DI_t=1,age_t \\le 45, M_t = 0)$","$P(H_t=2|DI_t=1,age_t > 45, M_t = 0)$","$P(H_t=1|DI_t=1,age_t \\le 45, M_t = 0)$","$P(H_t=1|DI_t=1,age_t > 45, M_t = 0)$","$P(H_t=0|DI_t=1,age_t \\le 45, M_t = 0)$","$P(H_t=0|DI_t=1,age_t > 45, M_t = 0)$",
  #                "$P(H_t=2|DI_t=1,age_t \\le 45, M_t = 1)$","$P(H_t=2|DI_t=1,age_t > 45, M_t = 1)$","$P(H_t=1|DI_t=1,age_t \\le 45, M_t = 1)$","$P(H_t=1|DI_t=1,age_t > 45, M_t = 1)$","$P(H_t=0|DI_t=1,age_t \\le 45, M_t = 1)$","$P(H_t=0|DI_t=1,age_t > 45, M_t = 1)$")
  eventDInames <- c("DI after Moderate Shock","DI after Severe Shock")
  
  moments_single<-c(cons2moments_single,workmoments_single)
  moments_married<-c(cons2moments_married,workmoments_married,spworkmoments)
  moments_all<-c(wagereg, spwagereg,wagevar, cons2moments_all,workmoments_married,workmoments_single,spworkmoments)
  weightmat_married<-c(1/(cons2se_married^2),1/(workse_married^2),1/(spworkse^2))
  weightmat_single<-c(1/(cons2se_single^2),1/(workse_single^2))
  weightmat <- c((1/(wagese^2)),(1/(spwagese^2)),(1/(wagevse^2)),1/(cons2se_all^2),1/(workse_married^2),1/(workse_single^2),1/(spworkse^2))
  
  if(nostockDI==FALSE){
    moments_single <- c(moments_single,stockDI_sing)
    weightmat_single <- c(weightmat_single,1/(stockDI_error_sing^2))
    moments_married <- c(moments_married,stockDI_mar)
    weightmat_married<-c(weightmat_married,1/(stockDI_error_mar^2))
    moments_all <- c(moments_all,stockDI_all)
    weightmat<- c(weightmat, 1/(stockDI_error_all^2))    
  }
  if(nocomp==FALSE) {
    moments_single <- c(moments_single,compDI_sing)
    weightmat_single<-c(weightmat_single,1/(compDI_error_sing^2))
    moments_married <- c(moments_married ,compDI_mar)
    weightmat_married<-c(weightmat_married,1/(compDI_error_mar^2))
    moments_all<- c(moments_all,compDI_all)
    weightmat<-c(weightmat, 1/(compDI_error_all^2))
  }
  if(noflow==FALSE) {
    moments_single <- c(moments_single,flowDI_sing)
    weightmat_single <- c(weightmat_single,1/(flowDI_error_sing^2))
    moments_married <- c(moments_married,flowDI_mar)
    weightmat_married<-c(weightmat_married,1/(flowDI_error_mar^2))
    moments_all <- c(moments_all,flowDI_all)
    weightmat<- c(weightmat, 1/(flowDI_error_all^2))
  }
  if(nocontflow==FALSE) {
    moments_single <- c(moments_single,contflowDI_sing)
    weightmat_single <- c(weightmat_single,1/(contflowDI_error_sing^2))
    moments_married <- c(moments_married,contflowDI_mar)
    weightmat_married<-c(weightmat_married,1/(contflowDI_error_mar^2))
    moments_all <- c(moments_all,contflowDI_all)
    weightmat<- c(weightmat, 1/(contflowDI_error_all^2))
  }
  if(noeventDI==FALSE){
    moments_single <- c(moments_single,eventDI_sing)
    weightmat_single <- c(weightmat_single,1/(eventDI_error_sing^2))
    moments_married <- c(moments_married,eventDI_mar)
    weightmat_married<-c(weightmat_married,1/(eventDI_error_mar^2))
    moments_all <- c(moments_all,eventDI_all)
    weightmat<- c(weightmat, 1/(eventDI_error_all^2))
    
  }
  
  
  
  if(onlysingle==TRUE) {
    datamoments <- moments_single
    weightmat<-diag(weightmat_single)
    consmoments<-cons2moments_single
    consse<-cons2se_single
    consnames<-consnames_single
    groupnames<-c("Single")
    stockDImoments<-stockDI_sing
    stockDIse <- stockDI_error_sing
    compDImoments<-compDI_sing
    compDIse <- compDI_error_sing
  } else if(onlymarried==TRUE) {
    datamoments<- moments_married
    weightmat<-diag(weightmat_married)
    consmoments<-cons2moments_married
    consse<-cons2se_married
    consnames<-consnames_married
    groupnames<-c("Married")
    stockDImoments<-stockDI_mar
    stockDIse <- stockDI_error_mar
    compDImoments<-compDI_mar
    compDIse <- compDI_error_mar
  } else{
    datamoments<-moments_all
    weightmat<-diag(weightmat)
    consmoments<-cons2moments_all
    consse<-cons2se_all
    consnames<-consnames_all
    groupnames<-c("Single","Married")
    stockDImoments<-stockDI_all
    stockDIse <- stockDI_error_all
    compDImoments<-compDI_all
    compDIse <- compDI_error_all
  }
  moments<-const_moments(output,shocks.wagenoise=shocks.wagenoise, shocks.spwagenoise=shocks.spwagenoise,
                         onlysingle=onlysingle,onlymarried=onlymarried,onlyFT=onlyFT,
                         nostockDI = nostockDI, noflow=noflow,nocomp=nocomp,nocontflow=nocontflow,
                         nohealthyDI=nohealthyDI,noeventDI=noeventDI,nospmoments=nospmoments,noworkDImoments=noworkDImoments,
                         consmoments_simple=consmoments_simple, workmoments_simple=workmoments_simple, DImoments_simple=DImoments_simple)
  
  
  objective<-t(moments-datamoments)%*%weightmat%*%as.matrix(moments-datamoments)*10^8
  print(objective)
  
  
  
  allmoments<-data.table(simulation=moments,
                         data = datamoments
  )
  allmoments[,diff:=simulation-data]
  extrases<-NULL
  if(nostockDI==FALSE) extrases<-c(extrases,simse(stockDIse))
  if(nocomp==FALSE) extrases<-c(extrases,simse(compDIse))
  if(noflow==FALSE) extrases<-c(extrases,simse(flowDI_error_all))
  if(nocontflow==FALSE) extrases<-c(extrases,simse(contflowDI_error_all))
  if(noeventDI==FALSE) extrases<-c(extrases,simse(eventDI_error_all))
  if(onlysingle==1){
    allmoments[,stderror:=c(simse(consse),simse(workse_single),simse(stockDIse),
                            extrases)]
    allmoments[,group:=c(rep("cons",length(consse)),
                         rep("work_sing",length(workse_single)),
                         rep("stockDI",length(stockDIse)),
                         rep("compDI",length(compDIse)*(nocomp==FALSE)),
                         rep("flowDI",length(flowDI_error_all)*(noflow==FALSE)),
                         rep("eventDI",length(eventDI_error_all)*(noeventDI==FALSE))
    )]
    allmoments[,variable:=c(consnames_single,
                            worknames,
                            stockDInames,
                            compDInames,
                            stockDInames,
                            rep(NA,length(eventDI_error_all)*(noeventDI==FALSE))
    )]
  } else if(onlymarried==1){
    allmoments[,stderror:=c(simse(consse),simse(workse_married),simse(spworkse),simse(stockDIse),
                            extrases)]
    allmoments[,group:=c(rep("cons",length(consse)),
                         rep("work_mar",length(workse_married)),
                         rep("spwork",length(spworkse)),
                         rep("stockDI",length(stockDIse)),
                         rep("compDI",length(compDIse)*(nocomp==FALSE)),
                         rep("flowDI",length(flowDI_error_all)*(noflow==FALSE)),
                         rep("eventDI",length(eventDI_error_all)*(noeventDI==FALSE))
    )]
    allmoments[,variable:=c(consnames_married,
                            worknames,
                            spworknames,
                            stockDInames,
                            compDInames,
                            stockDInames,
                            rep(NA,length(eventDI_error_all)*(noeventDI==FALSE))
    )]
  }else{
    allmoments[,stderror:=c(simse(wageregse),simse(spwageregse),simse(wagevse),simse(consse),simse(workse_married),simse(workse_single),simse(spworkse),
                            extrases)]
    allmoments[,group:=c(rep("wagereg",length(wageregse)),
                         rep("spwagereg",length(spwageregse)),
                         rep("wagevse",length(wagevse)),
                         rep("cons",length(consse)),
                         rep("work_mar",length(workse_married)),
                         rep("work_sing",length(workse_single)),
                         rep("spwork",length(spworkse)),
                         rep("stockDI",length(stockDIse)*(nostockDI==FALSE)),
                         rep("compDI",length(compDIse)*(nocomp==FALSE)),
                         rep("flowDI",length(flowDI_error_all)*(noflow==FALSE)),
                         rep("contflowDI",length(contflowDI_error_all)*(nocontflow==FALSE)),
                         rep("eventDI",length(eventDI_error_all)*(noeventDI==FALSE))
    )]
    if(nostockDI==TRUE) {
      stockDInames <- NULL
      stockmars<-NULL
    } else stockmars<-c(", single",", married")
    if(nocomp==TRUE) {
      compDInames<-NULL
      compmars<-NULL
    } else compmars<-c(", single",", married")
    if(noflow==TRUE) {
      flowDInames<-NULL
      flowmars<-NULL
    } else flowmars<-c(", single",", married")
    if(nocontflow==TRUE) {
      contflowDInames<-NULL
      contflowmars<-NULL
    } else contflowmars <- c(", single",",")
    # plotvarnames<-c(wagenames,
    #              spwagenames,
    #              wagevarnames,
    #              consnames,
    #              worknames,
    #              spworknames
    # )
    # if(nostockDI==FALSE) plotvarnames<-c(plotvarnames,stockDInames)
    # if(nocomp==FALSE) plotvarnames<-c(plotvarnames,compDInames)
    # if(noflow==FALSE) plotvarnames<-c(plotvarnames,flowDInames)
    # if(nocontflow==FALSE) plotvarnames<-c(plotvarnames,contflowDInames)
    # if(noeventDI==FALSE) plotvarnames<-c(plotvarnames,rep(NA,length(eventDI_error_all)*(noeventDI==FALSE)))
    # allmoments[,variable:=plotvarnames]
    
  }
  allmoments[,score:=diff/stderror]
  print(paste("Share moments not rejected:", allmoments[,mean(abs(score)<1.96)]))
  print("Moments rejected:")
  print(allmoments[abs(score)>1.96,])
  pdf(paste0(path,"modelmoment_distribution_",suffix,".pdf"))
  print(ggplot(data=allmoments)
        +geom_density(aes(x=score))
        +scale_x_continuous(breaks=pretty_breaks(n=12))
        +labs(x="Standard Deviations from Targeted Moments",y="Density"))
  dev.off()
  
  # allmoments[grepl(", single",variable),label:="Single"]
  # allmoments[grepl(", married",variable),label:="Partnered"]
  # allmoments[variable%in%c("Work x Disab (mod)","Work x Disab (sev)"),label:="RP"]
  # allmoments[variable%in%c("Work x Disab (mod)","Work x Disab (sev)"),label:="RP"]
  # allmoments[grepl("Spouse ",variable),label:="Spouse"]
  # allmoments[,variable:=gsub(", single","",variable)]
  # allmoments[,variable:=gsub(", married","",variable)]
  # allmoments[,variable:=gsub("Spouse ","",variable)]
  
  #allmoments[,label:=factor(label,levels=c("Partnered","Single","RP","Spouse"))]
  allmoments[group=="work_mar",label:="Partnered"]
  allmoments[group=="work_sing",label:="Single"]
  
  plotwagenames<-c("Low Type","Mid Type","High Type","Sev. Dis.","Mod. Dis.","Age","Age Sq.","Age \u2265 45","Age \u2265 45 and Sev. Dis.","Age \u2265 45 and Mod. Dis.")
  plotspwagenames<-c("Low Type","Mid Type","High Type","Disabled","Age","Age Sq.","Age \u2265 45","Age \u2265 45 and Disabled")
  plotwagevarnames<-wagevarnames
  plotconsnames_all<-c("Disability","Work","DI Receipt","Work X Disability","Spousal Disability","Spousal Work","Spousal Work X Disability")
  plotworknames<-c("Healthy, Age < 45","Healthy, Age \u2265 45","Mod. Dis., Age < 45", "Mod. Dis., Age \u2265 45","Sev. Dis., Age < 45","Sev. Dis., Age \u2265 45",
                   "Healthy, Age < 45","Healthy, Age \u2265 45","Mod. Dis., Age < 45", "Mod. Dis., Age \u2265 45","Sev. Dis., Age < 45","Sev. Dis., Age \u2265 45")
  plotspworknames <- c("Healthy, Age < 45","Healthy, Age \u2265 45", "Disabled, Age < 45", "Disabled, Age \u2265 45")
  plotcompDInames <- c("Sev. Dis., Age < 45","Sev. Dis., Age \u2265 45", "Mod. Dis., Age < 45","Mod. Dis., Age \u2265 45","Healthy, Age < 45","Healthy, Age \u2265 45",
                       "Sev. Dis., Age < 45","Sev. Dis., Age \u2265 45", "Mod. Dis., Age < 45","Mod. Dis., Age \u2265 45","Healthy, Age < 45","Healthy, Age \u2265 45")
  plotflowDInames <- c("Healthy, Age < 45","Mod. Dis., Age < 45","Sev. Dis., Age < 45","Healthy, Age \u2265 45","Mod. Dis., Age \u2265 45","Sev. Dis., Age \u2265 45",
                       "Healthy, Age < 45","Mod. Dis., Age < 45","Sev. Dis., Age < 45","Healthy, Age \u2265 45","Mod. Dis., Age \u2265 45","Sev. Dis., Age \u2265 45")
  ploteventDInames<-eventDInames
  #FIX THESE:
  allmoments[group=="wagereg",variable:=plotwagenames]
  allmoments[group=="spwagereg",variable:=plotspwagenames]
  allmoments[group=="wagevse",variable:=plotwagevarnames]
  allmoments[group=="cons",variable:=plotconsnames_all]
  allmoments[group=="work_mar",variable:=plotworknames[1:nrow(allmoments[group=="work_mar",])]]
  allmoments[group=="work_sing",variable:=plotworknames[1:nrow(allmoments[group=="work_sing",])]]
  allmoments[group=="spwork",variable:=plotspworknames]
  allmoments[group=="compDI",variable:=plotcompDInames[1:nrow(allmoments[group=="compDI",])]]
  allmoments[group=="flowDI",variable:=plotflowDInames[1:nrow(allmoments[group=="flowDI",])]]
  allmoments[group=="eventDI",variable:=ploteventDInames]
  allmoments[,variable:=factor(variable,levels=unique(c(plotwagenames,plotspwagenames,plotwagevarnames,plotconsnames_all,
                                                 plotworknames,plotspworknames,plotcompDInames,plotflowDInames,
                                                 ploteventDInames)))]
  
  allmoments[group=="eventDI",grouplab:="Event \n Study"]
  allmoments[group=="flowDI",grouplab:="DI Entry"]
  allmoments[group=="compDI",grouplab:="Share of \n DI Rolls"]
  allmoments[group=="work_mar",grouplab:="Work"]
  allmoments[group=="work_sing",grouplab:="Work (single)"]
  allmoments[group=="spwork",grouplab:="Spousal \n Work"]
  allmoments[group=="wagereg",grouplab:="Wage \n Regression"]
  allmoments[group=="spwagereg",grouplab:="Spousal Wage \n Regression"]
  allmoments[group=="wagevse",grouplab:="Wage \n Variation"]
  allmoments[group=="cons",grouplab:="Consumption \n Regression"]
  allmoments[,pvalue:=pnorm(-abs(diff/stderror))*2]
  
  allmoments[,grouplabtex:=gsub("\n ","",grouplab)]
  allmoments[,variabletex:=gsub("<","\\$<\\$",variable)]
  allmoments[grepl("\u2265",variabletex),variabletex:=gsub("\u2265","$ \\\\ge$",variable)]

  tab<-TR(c("","Data","Simulation","Diff","St. Error","P-Value"))+
    midrulep(list(c(2,6)))+
    TR("Panel A: Coefficients From a Log Wage Regression",surround = "\\textit{%s}",cspan=c(6))
  
  for(vb in allmoments[grouplabtex%in%"Wage Regression",variabletex]){
    row<-allmoments[grouplabtex%in%"Wage Regression"&variabletex==vb,]
    tab<-tab+
      TR(unlist(row[,variabletex]))%:%TR(unlist(row[,.(data,simulation,diff,stderror,pvalue)]),dec=3)
  }
  tab<-tab+vspace(5)+
    TR("Panel B: Coefficients From a Spousal Log Wage Regression",surround = "\\textit{%s}",cspan=c(6))
  for(vb in allmoments[grouplabtex%in%"Spousal Wage Regression",variabletex]){
    row<-allmoments[grouplabtex%in%"Spousal Wage Regression"&variabletex==vb,]
    tab<-tab+
      TR(unlist(row[,variabletex]))%:%TR(unlist(row[,.(data,simulation,diff,stderror,pvalue)]),dec=3)
  }
  
  tab<-tab+vspace(5)+
    TR("Panel C: Second-Order Moments in Log Wages",surround = "\\textit{%s}",cspan=c(6))
  for(vb in allmoments[grouplabtex%in%"Wage Variation",variabletex]){
    row<-allmoments[grouplabtex%in%"Wage Variation"&variabletex==vb,]
    tab<-tab+
      TR(unlist(row[,variabletex]))%:%TR(unlist(row[,.(data,simulation,diff,stderror,pvalue)]),dec=3)
  }
  tab<-tab+vspace(5)+
    TR("Panel D: Coefficients from a Log Consumption Regression",surround = "\\textit{%s}",cspan=c(6))
  for(vb in allmoments[grouplabtex%in%"Consumption Regression",variabletex]){
    row<-allmoments[grouplabtex%in%"Consumption Regression"&variabletex==vb,]
    tab<-tab+
      TR(unlist(row[,variabletex]))%:%TR(unlist(row[,.(data,simulation,diff,stderror,pvalue)]),dec=3)
  }
  saveRDS(tab,file=paste0(path,"momenttable_wagecons_",suffix,".RDS"))
  
    
  tab<-TR(c("","Data","Simulation","Diff","St. Error","P-Value"))+
    midrulep(list(c(2,6)))+
    TR("Panel A: Employment Shares",surround = "\\textit{%s}",cspan=c(6))
  
  for(vb in allmoments[grouplabtex%in%"Work",variabletex]){
    row<-allmoments[grouplabtex%in%"Work"&variabletex==vb,]
    tab<-tab+
      TR(unlist(row[,variabletex]))%:%TR(unlist(row[,.(data,simulation,diff,stderror,pvalue)]),dec=3)
  }
  tab<-tab+vspace(5)+
    TR("Panel B: Spousal Employment Shares",surround = "\\textit{%s}",cspan=c(6))
  for(vb in allmoments[grouplabtex%in%"Spousal Work",variabletex]){
    row<-allmoments[grouplabtex%in%"Spousal Work"&variabletex==vb,]
    tab<-tab+
      TR(unlist(row[,variabletex]))%:%TR(unlist(row[,.(data,simulation,diff,stderror,pvalue)]),dec=3)
  }
  tab<-tab+vspace(5)+
    TR("Panel C: Composition of DI Beneficiary Rolls",surround = "\\textit{%s}",cspan=c(6))
  for(vb in allmoments[grouplabtex%in%"Share of DI Rolls",variabletex]){
    row<-allmoments[grouplabtex%in%"Share of DI Rolls"&variabletex==vb,]
    tab<-tab+
      TR(unlist(row[,variabletex]))%:%TR(unlist(row[,.(data,simulation,diff,stderror,pvalue)]),dec=3)
  }
  tab<-tab+vspace(5)+
    TR("Panel D: DI Entry Rates",surround = "\\textit{%s}",cspan=c(6))
  for(vb in allmoments[grouplabtex%in%"DI Entry",variabletex]){
    row<-allmoments[grouplabtex%in%"DI Entry"&variabletex==vb,]
    tab<-tab+
      TR(unlist(row[,variabletex]))%:%TR(unlist(row[,.(data,simulation,diff,stderror,pvalue)]),dec=3)
  }
  tab<-tab+vspace(5)+
    TR("Panel E: Event Study Responses to Disability Onset",surround = "\\textit{%s}",cspan=c(6))
  for(vb in allmoments[grouplabtex%in%"Event Study",variabletex]){
    row<-allmoments[grouplabtex%in%"Event Study"&variabletex==vb,]
    tab<-tab+
      TR(unlist(row[,variabletex]))%:%TR(unlist(row[,.(data,simulation,diff,stderror,pvalue)]),dec=3)
  }
  
  saveRDS(tab,file=paste0(path,"momenttable_workDI_",suffix,".RDS"))
  
  
    
  ##These plots broke now that I have simplified eligibility:
  # pdf(paste0(path,"momentplots_",suffix,".pdf"))
  print(ggplot(data=allmoments[group=="cons",])
        +geom_col(aes(y=data,x=variable))
        +geom_errorbar(aes(ymin=simulation-1.96*stderror,
                           ymax=simulation+1.96*stderror,
                           x=variable))
        +geom_point(aes(y=simulation,x=variable))
        +facet_grid(label~., scales="free_y",
                    space="free_y",
                    switch="y")
        +theme(strip.placement="outside", strip.background=element_rect(fill="white",color="White"))
        +labs(x="",y="Coefficient")
        +coord_flip()
  )
  # 
  print(ggplot(data=allmoments[group%in%c("work_mar","work_sing"),])
        +geom_col(aes(y=data,x=variable))
        +geom_errorbar(aes(ymin=simulation-1.96*stderror,
                           ymax=simulation+1.96*stderror,
                           x=variable))
        +geom_point(aes(y=simulation,x=variable))
        +facet_grid(label~., scales="free_y",
                    space="free_y",
                    switch="y")
        +theme(strip.placement="outside", strip.background=element_rect(fill="white",color="White"))
        +labs(x="",y="Share Working")
        +coord_flip()
  )
  # 
  print(ggplot(data=allmoments[group%in%c("spwork"),])
        +geom_col(aes(y=data,x=variable))
        +geom_errorbar(aes(ymin=simulation-1.96*stderror,
                           ymax=simulation+1.96*stderror,
                           x=variable))
        +geom_point(aes(y=simulation,x=variable))
        +labs(x="",y="Share Working")
        +coord_flip()
  )
  # 
  # print(ggplot(data=allmoments[group%in%c("stockDI"),])
  #       +geom_col(aes(y=data,x=variable))
  #       +geom_errorbar(aes(ymin=simulation-1.96*stderror,
  #                          ymax=simulation+1.96*stderror,
  #                          x=variable))
  #       +geom_point(aes(y=simulation,x=variable))
  #       +facet_grid(label~., scales="free_y",
  #                   space="free_y",
  #                   switch="y")
  #       +theme(strip.placement="outside", strip.background=element_rect(fill="white",color="White"))
  #       +labs(x="",y="Share Working")
  #       +coord_flip()
  # )
  # 
  print(ggplot(data=allmoments[group%in%c("flowDI"),])
        +geom_col(aes(y=data,x=variable))
        +geom_errorbar(aes(ymin=simulation-1.96*stderror,
                           ymax=simulation+1.96*stderror,
                           x=variable))
        +geom_point(aes(y=simulation,x=variable))
        +labs(x="",y="Share entering DI")
        +coord_flip()
  )
  # dev.off()
  
  print(ggplot(data=allmoments[group%in%c("compDI"),])
        +geom_col(aes(y=data,x=variable))
        +geom_errorbar(aes(ymin=simulation-1.96*stderror,
                           ymax=simulation+1.96*stderror,
                           x=variable))
        +geom_point(aes(y=simulation,x=variable))
        +labs(x="",y="Share of DI Beneficiaries")
        +coord_flip()
  )
  
 
  allmoments[,grouplab:=factor(grouplab,levels=c("Work", "Work (single)","Spousal \n Work", 
                                                    "Share of \n DI Rolls", "DI Entry","Event \n Study",
                                                    "Wage \n Regression","Spousal Wage \n Regression","Wage \n Variation","Consumption \n Regression"
  ))]
  
  allmoments[variable=="Age"&group%in%c("wagereg","spwagereg"),data:=data*20]
  allmoments[variable=="Age"&group%in%c("wagereg","spwagereg"),simulation:=simulation*20]
  allmoments[variable=="Age"&group%in%c("wagereg","spwagereg"),diff:=diff*20]
  allmoments[variable=="Age"&group%in%c("wagereg","spwagereg"),stderror:=stderror*20]
  #Note: age sq. alreay multiplied by 100
  allmoments[variable=="Age Sq."&group%in%c("wagereg","spwagereg"),data:=data*4]
  allmoments[variable=="Age Sq."&group%in%c("wagereg","spwagereg"),simulation:=simulation*4]
  allmoments[variable=="Age Sq."&group%in%c("wagereg","spwagereg"),diff:=diff*4]
  allmoments[variable=="Age Sq."&group%in%c("wagereg","spwagereg"),stderror:=stderror*4]
  
  allmoments[variable=="Age",variable:="Age / 20"]
  allmoments[variable=="Age Sq.",variable:="(Age / 20) Sq."]
  
#  allmoments[grouplab%in%c("Wage \n Regression","Spousal Wage \n Regression"),collabs:=" "]
#  allmoments[grouplab%in%c("Consumption \n Regression","Wage \n Variation"),collabs:="  "]
  
   cairo_pdf(paste0(path,"momentfit_regsummary_",suffix,".pdf"))
  print(ggplot(data=allmoments[group%in%c("wagereg","spwagereg","wagevse","cons"),])
        +geom_col(aes(y=simulation,x=variable))
        +geom_errorbar(aes(ymin=data-1.96*stderror,
                           ymax=data+1.96*stderror,
                           x=variable))
        +geom_point(aes(y=data,x=variable))
        +labs(x="",y="")
        +coord_flip()
        +facet_grid(rows=vars(grouplab),#cols=vars(collab),
                    scales="free_y", space="free_y", switch="y"
                    #labeller=labeller(group=grouplabs)
        )+
          theme(strip.text.y=element_text(size=14, angle=270),
                strip.background = element_blank(),
                axis.title.x = element_text(size=14),
                axis.title.y = element_text(size=14),
                axis.text.x = element_text(size=12),
                axis.text.y = element_text(size=12),
                strip.placement="outside")
  )
  dev.off()
  
  
  
  cairo_pdf(paste0(path,"momentfit_regsummary1_",suffix,".pdf"))
  print(ggplot(data=allmoments[group%in%c("wagereg","spwagereg"),])
        +geom_col(aes(y=simulation,x=variable))
        +geom_errorbar(aes(ymin=data-1.96*stderror,
                           ymax=data+1.96*stderror,
                           x=variable))
        +geom_point(aes(y=data,x=variable))
        +labs(x="",y="")
        +coord_flip()
        +facet_grid(rows=vars(grouplab),#cols=vars(collab),
                    scales="free_y", space="free_y", switch="y"
                    #labeller=labeller(group=grouplabs)
        )+
          theme(#strip.text.y=element_text(size=14, angle=270),
                strip.background = element_blank(),
                #axis.title.x = element_text(size=14),
                #axis.title.y = element_text(size=14),
                #axis.text.x = element_text(size=12),
                #axis.text.y = element_text(size=12),
                strip.placement="outside")
  )
  dev.off()
  
  cairo_pdf(paste0(path,"momentfit_regsummary2_",suffix,".pdf"))
  print(ggplot(data=allmoments[group%in%c("wagevse","cons"),])
        +geom_col(aes(y=simulation,x=variable))
        +geom_point(aes(y=data,x=variable))
        +geom_errorbar(aes(ymin=data-1.96*stderror,
                           ymax=data+1.96*stderror,
                           x=variable))
        +labs(x="",y="")
        +coord_flip()
        +facet_grid(rows=vars(grouplab),#cols=vars(collab),
                    scales="free_y", space="free_y", switch="y"
                    #labeller=labeller(group=grouplabs)
        )+
          theme(#strip.text.y=element_text(size=14, angle=270),
                strip.background = element_blank(),
                #axis.title.x = element_text(size=14),
                #axis.title.y = element_text(size=14),
                #axis.text.x = element_text(size=12),
                #axis.text.y = element_text(size=12),
                strip.placement="outside")
  )
  dev.off()
  
  cairo_pdf(paste0(path,"momentfit_regsummarynormalized_",suffix,".pdf"))
  print(ggplot(data=allmoments[group%in%c("wagereg","spwagereg","wagevse","cons"),])
        +geom_col(aes(y=(data-simulation)/stderror,x=variable))
        +geom_hline(aes(yintercept=1.96),linetype='dashed')
        +geom_hline(aes(yintercept=-1.96),linetype='dashed')
        +labs(x="",y="t-statistic")
        +coord_flip()
        +facet_grid(rows=vars(grouplab),#cols=vars(collab),
                    scales="free_y", space="free_y", switch="y"
                    #labeller=labeller(group=grouplabs)
        )+
          theme(strip.text.y=element_text(size=14, angle=270),
                strip.background = element_blank(),
                axis.title.x = element_text(size=14),
                axis.title.y = element_text(size=14),
                axis.text.x = element_text(size=12),
                axis.text.y = element_text(size=12),
                strip.placement="outside")
  )
  dev.off()
  
  cairo_pdf(paste0(path,"momentfit_regsummarynormalized1_",suffix,".pdf"))
  print(ggplot(data=allmoments[group%in%c("wagereg","spwagereg"),])
        +geom_col(aes(y=(data-simulation)/stderror,x=variable))
        +geom_hline(aes(yintercept=1.96),linetype='dashed')
        +geom_hline(aes(yintercept=-1.96),linetype='dashed')
        +labs(x="",y="t-statistic")
        +coord_flip()
        +facet_grid(rows=vars(grouplab),#cols=vars(collab),
                    scales="free_y", space="free_y", switch="y"
                    #labeller=labeller(group=grouplabs)
        )+
          theme(strip.text.y=element_text(size=14, angle=270),
                strip.background = element_blank(),
                axis.title.x = element_text(size=14),
                axis.title.y = element_text(size=14),
                axis.text.x = element_text(size=12),
                axis.text.y = element_text(size=12),
                strip.placement="outside")
  )
  dev.off()
  
  cairo_pdf(paste0(path,"momentfit_regsummarynormalized2_",suffix,".pdf"))
  print(ggplot(data=allmoments[group%in%c("wagevse","cons"),])
        +geom_col(aes(y=(data-simulation)/stderror,x=variable))
        +geom_hline(aes(yintercept=1.96),linetype='dashed')
        +geom_hline(aes(yintercept=-1.96),linetype='dashed')
        +labs(x="",y="t-statistic")
        +coord_flip()
        +facet_grid(rows=vars(grouplab),#cols=vars(collab),
                    scales="free_y", space="free_y", switch="y"
                    #labeller=labeller(group=grouplabs)
        )+
          theme(strip.text.y=element_text(size=14, angle=270),
                strip.background = element_blank(),
                axis.title.x = element_text(size=14),
                axis.title.y = element_text(size=14),
                axis.text.x = element_text(size=12),
                axis.text.y = element_text(size=12),
                strip.placement="outside")
  )
  dev.off()
  
  
  cairo_pdf(paste0(path,"momentfit_summary_",suffix,".pdf"))
  print(ggplot(data=allmoments[group%in%c("eventDI","flowDI","compDI","work_mar","work_sing","spwork"),])
        +geom_col(aes(y=simulation,x=variable))
        +geom_point(aes(y=data,x=variable))
        +geom_errorbar(aes(ymin=data-1.96*stderror,
                           ymax=data+1.96*stderror,
                           x=variable))
        +labs(x="",y="Share")
        +coord_flip()
        +facet_grid(rows=vars(grouplab), scales="free_y", space="free_y", switch="y"
                    #labeller=labeller(group=grouplabs)
        )+
          theme(strip.text.y=element_text(size=14, angle=270),
                strip.background = element_blank(),
                axis.title.x = element_text(size=14),
                axis.title.y = element_text(size=14),
                axis.text.x = element_text(size=12),
                axis.text.y = element_text(size=12),
                strip.placement="outside")
  )
  dev.off()
  
  
  cairo_pdf(paste0(path,"momentfit_summary1_",suffix,".pdf"))
  print(ggplot(data=allmoments[group%in%c("compDI","work_mar","work_sing","spwork"),])
        +geom_col(aes(y=simulation,x=variable))
        +geom_point(aes(y=data,x=variable))
        +geom_errorbar(aes(ymin=data-1.96*stderror,
                           ymax=data+1.96*stderror,
                           x=variable))
        +labs(x="",y="")
        +coord_flip()
        +facet_grid(rows=vars(grouplab), scales="free_y", space="free_y", switch="y"
                    #labeller=labeller(group=grouplabs)
        )+
          theme(#strip.text.y=element_text(size=14, angle=270),
                strip.background = element_blank(),
#                axis.title.x = element_text(size=14),
#                axis.title.y = element_text(size=14),
#                axis.text.x = element_text(size=12),
#                axis.text.y = element_text(size=12),
                strip.placement="outside")
  )
  dev.off()
  
  
  cairo_pdf(paste0(path,"momentfit_summary2_",suffix,".pdf"))
  print(ggplot(data=allmoments[group%in%c("eventDI","flowDI"),])
        +geom_col(aes(y=simulation,x=variable))
        +geom_point(aes(y=data,x=variable))
        +geom_errorbar(aes(ymin=data-1.96*stderror,
                           ymax=data+1.96*stderror,
                           x=variable))
        +labs(x="",y="")
        +coord_flip()
        +facet_grid(rows=vars(grouplab), scales="free_y", space="free_y", switch="y"
                    #labeller=labeller(group=grouplabs)
        )+
          theme(#strip.text.y=element_text(size=14, angle=270),
                strip.background = element_blank(),
#                axis.title.x = element_text(size=14),
#                axis.title.y = element_text(size=14),
#                axis.text.x = element_text(size=12),
#                axis.text.y = element_text(size=12),
                strip.placement="outside")
  )
  dev.off()
  
  cairo_pdf(paste0(path,"momentfit_summarynormalized_",suffix,".pdf"))
  print(ggplot(data=allmoments[group%in%c("eventDI","flowDI","compDI","work_mar","work_sing","spwork"),])
        +geom_col(aes(y=(data-simulation)/stderror,x=variable))
        +geom_hline(aes(yintercept=1.96),linetype='dashed')
        +geom_hline(aes(yintercept=-1.96),linetype='dashed')
        +labs(x="",y="t-statistic")
        +coord_flip()
        +facet_grid(rows=vars(grouplab), scales="free_y", space="free_y", switch="y"
                    #labeller=labeller(group=grouplabs)
        )+
          theme(strip.text.y=element_text(size=14, angle=270),
                strip.background = element_blank(),
                axis.title.x = element_text(size=14),
                axis.title.y = element_text(size=14),
                axis.text.x = element_text(size=12),
                axis.text.y = element_text(size=12),
                strip.placement="outside")
  )
  dev.off()
  
  cairo_pdf(paste0(path,"momentfit_summarynormalized1_",suffix,".pdf"))
  print(ggplot(data=allmoments[group%in%c("compDI","work_mar","work_sing","spwork"),])
        +geom_col(aes(y=(data-simulation)/stderror,x=variable))
        +geom_hline(aes(yintercept=1.96),linetype='dashed')
        +geom_hline(aes(yintercept=-1.96),linetype='dashed')
        +labs(x="",y="t-statistic")
        +coord_flip()
        +facet_grid(rows=vars(grouplab), scales="free_y", space="free_y", switch="y"
                    #labeller=labeller(group=grouplabs)
        )+
          theme(strip.text.y=element_text(size=14, angle=270),
                strip.background = element_blank(),
                axis.title.x = element_text(size=14),
                axis.title.y = element_text(size=14),
                axis.text.x = element_text(size=12),
                axis.text.y = element_text(size=12),
                strip.placement="outside")
  )
  dev.off()
  
  cairo_pdf(paste0(path,"momentfit_summarynormalized2_",suffix,".pdf"))
  print(ggplot(data=allmoments[group%in%c("eventDI","flowDI"),])
        +geom_col(aes(y=(data-simulation)/stderror,x=variable))
        +geom_hline(aes(yintercept=1.96),linetype='dashed')
        +geom_hline(aes(yintercept=-1.96),linetype='dashed')
        +labs(x="",y="t-statistic")
        +coord_flip()
        +facet_grid(rows=vars(grouplab), scales="free_y", space="free_y", switch="y"
                    #labeller=labeller(group=grouplabs)
        )+
          theme(strip.text.y=element_text(size=14, angle=270),
                strip.background = element_blank(),
                axis.title.x = element_text(size=14),
                axis.title.y = element_text(size=14),
                axis.text.x = element_text(size=12),
                axis.text.y = element_text(size=12),
                strip.placement="outside")
  )
  dev.off()
  
  
  print(ggplot(data=allmoments[group%in%c("spwagereg"),])
        +geom_col(aes(y=data,x=variable))
        +geom_errorbar(aes(ymin=simulation-1.96*stderror,
                           ymax=simulation+1.96*stderror,
                           x=variable))
        +geom_point(aes(y=simulation,x=variable))
        +labs(x="",y="Regression Coefficient")
        +coord_flip()
  )
  
  print(ggplot(data=allmoments[group%in%c("wagevse"),])
        +geom_col(aes(y=data,x=variable))
        +geom_errorbar(aes(ymin=simulation-1.96*stderror,
                           ymax=simulation+1.96*stderror,
                           x=variable))
        +geom_point(aes(y=simulation,x=variable))
        +labs(x="",y="Regression Coefficient")
        +coord_flip()
  )
  
  ########UNTARGETTED MOMENTS:
  
  output<-output[order(Work,spWork),]
  mom.jointwork<-c(output[age<=62,mean(Work==0&spWork==0)],output[age<=62,mean(Work==0&spWork==1)],
                   output[age<=62,mean(Work==1&spWork==0)], output[age<=62,mean(Work==1&spWork==1)])
  mom.jointworkpart<-c(output[age<=62,mean(Workpart==0&spWorkpart==0)],output[age<=62,mean(Workpart==0&spWorkpart==1)],
                       output[age<=62,mean(Workpart==1&spWorkpart==0)], output[age<=62,mean(Workpart==1&spWorkpart==1)])
  tblplot<-data.table(cbind(V1=c("Neither Head nor Spouse Works","Only Spouse Works","Only Head Works","Both Head and Spouse Work"),V2=jointworkmoments,V3=mom.jointwork,V4="Full"))
  tblplot<-rbind(tblplot,data.table(cbind(V1=c("Neither Head nor Spouse Works","Only Spouse Works","Only Head Works","Both Head and Spouse Work"),V2=jointworkpartmoments,V3=mom.jointworkpart,V4="Part")))
  setnames(tblplot,c("V1","V2","V3","V4"),c("Cell","Data","Simulation","Type"))
  
  print(ggplot(data=melt(tblplot[Type=="Full",],id.vars="Cell")[variable!="Type",]) 
        +geom_bar(position="dodge",stat='identity',aes(y=as.numeric(value),x=Cell,fill=variable))
        +labs(x="", y="Share")
        +theme(axis.text=element_text(color="black"),
               axis.text.x=element_text(angle=20,hjust=1),
               text= element_text(color='black'),
               plot.title = element_text(size=15,color='black',hjust=0.5),legend.justification=c(0,1),legend.position=c(0.65,0.95),
               legend.background=element_rect(color="black")))
  
  print(ggplot(data=melt(tblplot[Type=="Part",],id.vars="Cell")[variable!="Type",]) 
        +geom_bar(position="dodge",stat='identity',aes(y=as.numeric(value),x=Cell,fill=variable))
        +labs(x="", y="Share")
        +theme(axis.text=element_text(color="black"),
               axis.text.x=element_text(angle=20,hjust=1),
               text= element_text(color='black'),
               plot.title = element_text(size=15,color='black',hjust=0.5),legend.justification=c(0,1),legend.position=c(0.65,0.95),
               legend.background=element_rect(color="black")))
  if(onlyFT==FALSE) {
    tbl<-xtable(rbind(c("Full-Time","Data","Simulation","Diff","SE"),cbind(c("Neither Head nor Spouse Works","Only Spouse Works","Only Head Works","Both Head and Spouse Work"),round(jointworkmoments,3),round(mom.jointwork,3),sigstar(jointworkmoments-mom.jointwork,jointworkse),round(simse(jointworkse),3)),
                      c("Part-Time","Data","Simulation","Diff","SE"),cbind(c("Neither Head nor Spouse Works","Only Spouse Works","Only Head Works","Both Head and Spouse Work"),round(jointworkpartmoments,3),round(mom.jointworkpart,3),sigstar(jointworkpartmoments-mom.jointworkpart,jointworkpartse),round(simse(jointworkpartse),3))),type="latex",digits=3)
    hrows<-c(1,5,6,nrow(tbl))
  }
  else  {
    tbl<-xtable(rbind(c("Full-Time","Data","Simulation","Diff","SE"),
                      cbind(c("Neither Head nor Spouse Works","Only Spouse Works","Only Head Works","Both Head and Spouse Work"),round(jointworkmoments,3),round(mom.jointwork,3),sigstar(jointworkmoments-mom.jointwork,jointworkse),round(simse(jointworkse),3))
    ),type="latex",digits=3)
    hrows<-c(1,nrow(tbl))
    
  }
  #rownames(tbl)<-c("Neither Work Full-Time","Spouse Works Full-Time","Head Works Full-Time","Both Work Full-Time")
  #colnames(tbl)<-c("Data","Simulation","Diff")
  jointbl<-TR(c("","Data","Simulation","Diff","St. Error"))+
    midrulep(list(c(2,2),c(3,3),c(4,4),c(5,5)))+
    TR("Neither Head nor Spouse Works")%:%TR(c(jointworkmoments[1],mom.jointwork[1]),dec=3)%:%
    TR(jointworkmoments[1]-mom.jointwork[1],pvalue = myp(-abs(jointworkmoments[1]-mom.jointwork[1])/simse(jointworkse[1])),dec=3)%:%
    TR(simse(jointworkse[1]),dec=3)+
    TR("Only Spouse Works")%:%TR(c(jointworkmoments[2],mom.jointwork[2]),dec=3)%:%
    TR(jointworkmoments[2]-mom.jointwork[2],pvalue = myp(-abs(jointworkmoments[2]-mom.jointwork[2])/simse(jointworkse[2])),dec=3)%:%
    TR(simse(jointworkse[2]),dec=3)+
    TR("Only Head Works")%:%TR(c(jointworkmoments[3],mom.jointwork[3]),dec=3)%:%
    TR(jointworkmoments[3]-mom.jointwork[3],pvalue = myp(-abs(jointworkmoments[3]-mom.jointwork[3])/simse(jointworkse[3])),dec=3)%:%
    TR(simse(jointworkse[3]),dec=3)+
    TR("Both Head and Spouse Work")%:%TR(c(jointworkmoments[4],mom.jointwork[4]),dec=3)%:%
    TR(jointworkmoments[4]-mom.jointwork[4],pvalue = myp(-abs(jointworkmoments[4]-mom.jointwork[4])/simse(jointworkse[4])),dec=3)%:%
    TR(simse(jointworkse[4]),dec=3)
  saveRDS(jointbl,paste0(path,"jointwork_",suffix,".RDS"))
    
  align(tbl)<-"ll|cccc"
  print(tbl,file=paste0(path,"jointworkfit_",suffix,".tex"),tabular.environment='tabular',floating=FALSE,
        include.colnames=FALSE,include.rownames=FALSE, only.contents=TRUE,
        hline.after=hrows,sanitize.text.function = function(x) x)
  
  rm(output)
  
  temp<-as.data.table(read.csv("./output/headsev_agebal_level_applyorDI.csv"))
  temp[,married:=grepl("married",X)]
  temp[,X:=gsub(":marriedTRUE","",X)]
  temp[,X:=as.numeric(gsub("as\\.factor\\(time\\)","",X))]
  setnames(temp,"X","time")
  
  #Comparing application/acceptance to SIPP data:
  regdata<-copy(simdata)
  regdata[,age_limit:=min(age + 9999*(Health ==1)),by=.(i,Type)]
  regdata[,age_sev:=min(age + 9999*(Health !=3)),by=.(i,Type)]
  regdata[,age_work:=min(age + 9999*(Work ==0)),by=.(i,Type)]
  regdata<-regdata[age_limit - age_sev >= -4 &
                  age_work < age_limit &
                     age_limit <=62,]
  regdata[,time:=age-age_limit]
  regdata<-regdata[time>=-4 & time<=4,]
  #regdata[,agebin:=floor(age_limit/10)*10]
  # regdata[,pval:=feols(as.formula(paste0("married~ 1 | interaction(as.factor(time_limit),as.factor(agebin))")),
  #                                                data = regdata)$fitted.values]
  # regdata[married == 0 & pval < 1 & pval > 0,
  #             pweight:=pval/(1-pval)]
  # regdata[married == 1& pval < 1 & pval > 0, pweight:=1]

  plotdata<-regdata[,mean(Apply == 1 | yearDI == 1),by=.(time)]
  
  
  pdf(paste0(path,"applyratefit_",suffix,".pdf"))
  print(
    ggplot()
    +geom_line(data=plotdata,aes(x=time,y=V1,linetype="Simulation",color="Simulation"))
    +geom_point(data=plotdata,aes(x=time,y=V1,color="Simulation"))
    +geom_ribbon(data=temp,aes(x=time,ymax=Estimate + 1.96*Std..Error ,ymin=Estimate - 1.96*Std..Error,linetype="Data",fill="Data",color="Data"),alpha=0.4)
    +geom_hline(aes(yintercept=0),linetype="dashed")
+fitrules
#    +scale_x_continuous(breaks=integer_breaks(n=5))
    +labs(x="Time since Severe Shock",y="Share Applying or Receiving DI", linetype="",color="",fill="")
    +theme(legend.position="bottom")
  )
  dev.off()
  
  regdata<-copy(simdata)
  #comparing allowance probabilities from first application, to French and Song (2014):
  regdata<-regdata[,.(ageapply=min(age+99999*(Apply!=1)),
                      age_firstDI=min(age + 99999*(yearDI != 1 | age > 62))),by=i]
  regdata[ageapply>99,ageapply:=NA]
  plotdata<-data.table(age_relapply=0:10,V1=0)
  for(a in 0:10){
    #probability that an application led to DI award within 'a' years:
    plotdata[age_relapply==a,V1:=mean(regdata[, age_firstDI-ageapply <= a],na.rm=TRUE)]
  }
  
  #Including people who end in retirement
  regdata<-copy(simdata)
  regdata<-regdata[,.(ageapply=min(age+99999*(Apply!=1)),
                      age_firstDI=min(age + 99999*(yearDI != 1 & age <= 62 ))),by=i]
  regdata[ageapply>99,ageapply:=NA]
  plotdata[,V2:=0]
  for(a in 0:10){
    #probability that an application led to DI award within 'a' years:
    plotdata[age_relapply==a,V2:=mean(regdata[, age_firstDI-ageapply <= a],na.rm=TRUE)]
  }
  

  
  
  regdata<-copy(simdata)
  regdata<-regdata[order(i,time),]
  regdata[,lw:=log(Wage*2000*Work)]
  bounds<-quantile(regdata[Work==1&select==1,]$lw,probs=c(0,1))
  #Comparing simulated vs actual wage reg, without selection correction
  regdata[select==1 & Work==1,difflw := lw - shift(lw,n=1,type="lag"),by=i]
  regdata[select==1 & Work==1,diffage := age - shift(age,n=1,type="lag"),by=i]
  regdata[select==1 & Work==1,diffage2 := diffage^2]
  regdata[select==1 & Work==1,diffsev := Health==3 - shift(Health==3,n=1,type="lag"),by=i]
  regdata[select==1 & Work==1,diffmod := Health==2 - shift(Health==2,n=1,type="lag"),by=i]
  regdata[select==1 & Work==1,diffmarried := single==0 - shift(single==0,n=1,type="lag"),by=i]
  mom.wage <- feols(difflw ~ diffsev + diffmod + diffage + diffage2 + diffmarried, data=regdata[select==1&Work==1,])$coefficients
  
  plotdata<-regdata[Work==1&select==1 & lw >= bounds[1] & lw <= bounds[2],
                    mean(lw),by=age]
  meanval<-mean(plotdata$V1)
  print(ggplot(data=plotdata)+ 
          geom_point(aes(x=age,y=V1-meanval)))
  
  write.dta(plotdata,paste0(path,'modelWage_spouse_',suffix,'.dta'))
  
  regdata<-copy(simdata)
  regdata[,splw:=log(spWage*2000)]
  bounds<-quantile(regdata[select==1&spWork==1,]$splw,probs=c(0,1))
  #Comparing simulated vs actual wage reg, without selection correction
  regdata[select==1 & spWork==1,diffsplw := splw - shift(splw,n=1,type="lag"),by=i]
  regdata[select==1 & spWork==1,diffsp_age := age - shift(age,n=1,type="lag"),by=i]
  regdata[select==1 & spWork==1,diffsp_age2 := diffsp_age^2]
  regdata[select==1 & spWork==1,diffsp_dis := spHealth==2 - shift(spHealth==2,n=1,type="lag"),by=i]
  mom.spwage <- feols(diffsplw ~ diffsp_dis + diffsp_age + diffsp_age2, data=regdata[select==1&spWork==1 & single==0,])$coefficients
  
  plotdata<-regdata[spWork==1&select==1 & splw >= bounds[1] & splw <= bounds[2],
                    mean(splw),by=age]
  print(ggplot(data=plotdata)+ 
          geom_point(aes(x=age,y=V1)))
  
  write.dta(plotdata,paste0(path,'modelspWage_spouse_',suffix,'.dta'))
  
  # tbl<-TR(c("","Data","Simulation","Diff","St. Error"))+
  #   midrulep(list(c(2,2),c(3,3),c(4,4),c(5,5)))
  # for(row in 1:length(wagevals_noselection)){
  #   tbl<-tbl + TR(wagenames[row])%:%TR(c(wagevals_noselection[row,1],mom.wage[row],dec=3))%:%
  #     TR((wagevals_noselection[row,1]-mom.wage[row]),pvalues=myp(-abs(wagevals_noselection[row,1]-mom.wage[row])/simse(wagevals_noselection[row,2])),dec=3)%:%
  #     TR(simse(wagevals_noselection[row,2]),dec=3)
  # }
  # saveRDS(tbl,file=paste0(path,"wagefit_",suffix,".RDS"))
  # 
  # tbl<-TR(c("","Data","Simulation","Diff","St. Error"))+
  #   midrulep(list(c(2,2),c(3,3),c(4,4),c(5,5)))
  # for(row in 1:length(spwagevals_noselection)){
  #   tbl<-tbl + TR(spwagenames[row])%:%TR(c(spwagevals_noselection[row,1],mom.spwage[row],dec=3))%:%
  #     TR((spwagevals_noselection[row,1]-mom.spwage[row]),pvalues=myp(-abs(spwagevals_noselection[row,1]-mom.spwage[row])/simse(spwagevals_noselection[row,2])),dec=3)%:%
  #     TR(simse(spwagevals_noselection[row,2]),dec=3)
  # }
  # saveRDS(tbl,file=paste0(path,"spwagefit_",suffix,".RDS"))
  # 
  
  regdata<-copy(simdata)
  bounds<-quantile(regdata[select==1,Wage*Work*2000],probs=c(0,1))
  plotdata<-regdata[select==1 & Wage*Work*2000 >= bounds[1] & Wage*Work*2000 <= bounds[2]
                    ,mean(Wage*Work*2000),by=age]
  print(ggplot(data=plotdata)+ 
          geom_point(aes(x=age,y=V1)))
  
  write.dta(plotdata,paste0(path,'modelEarnings_spouse_',suffix,'.dta'))
  
  regdata<-copy(simdata)
  bounds<-quantile(regdata[select==1,spWage*spWork*2000],probs=c(0,1))
  plotdata<-regdata[select==1 & spWage*spWork*2000 >= bounds[1] & spWage*spWork*2000 <= bounds[2],
                    mean(spWage*spWork*2000),by=age]
  print(ggplot(data=plotdata)+ 
          geom_point(aes(x=age,y=V1)))
  
  write.dta(plotdata,paste0(path,'modelspEarnings_spouse_',suffix,'.dta'))
  
  bounds<-quantile(regdata[select==1,NetInc],probs=c(0,1))
  plotdata<-regdata[select==1 & NetInc >=bounds[1] & NetInc <=bounds[2],
                    mean(NetInc),by=.(Health,age)]
  print(ggplot(data=plotdata)+ 
          geom_point(aes(x=age,y=V1,group=as.factor(Health),color=as.factor(Health))))
  
  regdata<-copy(simdata)
  bounds<-quantile(regdata[select==1,log(GrossOutput + Transfers)],probs=c(0,1))
  plotdata<-regdata[select==1 & log(GrossOutput + Transfers)>= bounds[1] & 
                      log(GrossOutput + Transfers) <= bounds[2] ,
                    mean(log(GrossOutput + Transfers)),by=.(age,single)]
  print(ggplot(data=plotdata)+ 
          geom_point(aes(x=age,y=V1, group=single)))
  
  write.dta(plotdata,paste0(path,'modelGrossIncome_spouse_',suffix,'.dta'))
  
  #keeping post-retirement years:
  plotdata<-copy(simdata)
  bounds<-quantile(plotdata[selectC==1,Asset/1000],probs=c(0,1))
  
  plotdata[,enterDI:=yearDI==1&c(NA,yearDI[-.N])==0&time<62*params$agelength]
  plotdata[yearDI==1&enterDI!=1,enterDI:=NA]
  plotdata<-plotdata[selectC==1,]
  plotdata<-plotdata[Asset/1000 >=  bounds[1] & 
                      Asset/1000 <= bounds[2],median(Asset/1000),by=.(age, single)]
  print(ggplot(data=plotdata)+ 
          geom_point(aes(x=age,y=V1)))
  write.dta(plotdata,paste0(path,'modelAssets_spouse_',suffix,'.dta'))
  
  #keeping post-retirement years:
  plotdata<-copy(simdata)
  plotdata[,enterDI:=yearDI==1&c(NA,yearDI[-.N])==0&time<62*params$agelength]
  plotdata[yearDI==1&enterDI!=1,enterDI:=NA]
  plotdata<-plotdata[select==1,]
  plotdata<-plotdata[,median(Asset/1000),by=.(age,Health)]
  print(ggplot(data=plotdata)+ 
          geom_point(aes(x=age,y=V1,group=as.factor(Health),color=as.factor(Health))))
  write.dta(plotdata,paste0(path,'modelAssets_byHealth_spouse_',suffix,'.dta'))
  
  #keeping post-retirement years:
  plotdata<-copy(simdata)
  plotdata[,enterDI:=yearDI==1&c(NA,yearDI[-.N])==0&time<62*params$agelength]
  plotdata[yearDI==1&enterDI!=1,enterDI:=NA]
  plotdata<-plotdata[select==1,]
  plotdata<-plotdata[,median(Asset/1000),by=.(age,Type)]
  print(ggplot(data=plotdata)+ 
          geom_point(aes(x=age,y=V1,group=as.factor(Type),color=as.factor(Type))))
  write.dta(plotdata,paste0(path,'modelAssets_bytype_spouse_',suffix,'.dta'))
  
  
  meanval<-regdata[selectC==1,mean(log(C),trim=0)]
  bounds<-quantile(regdata[selectC==1,log(C)],probs=c(0,1))
  plotdata<-regdata[selectC==1 & log(C) >= bounds[1] & log(C) <= bounds[2],.(Ceq=mean(log(yearcons)),C=mean(log(C))),by=.(age,single)]
  print(ggplot(data=plotdata)+ 
#          geom_point(aes(x=age,y=Ceq))+
          geom_point(aes(x=age,y=C-meanval, group = single)))
  write.dta(plotdata,paste0(path,'modelSpending_spouse',suffix,'.dta'))
  
plotdata<-NULL
for(t in unique(regdata$Type)){
  meanval<-regdata[selectC==1& Type==t,mean(log(C),trim=0)]
  bounds<-quantile(regdata[selectC==1& Type==t,log(C)],probs=c(0,1))
  plotdata<-rbind(plotdata,
                  regdata[selectC==1 & log(C) >= bounds[1] & log(C) <= bounds[2]& Type==t,.(Ceq=mean(log(yearcons)),C=mean(log(C))),by=.(age,Type)]
  )
}
  print(ggplot(data=plotdata)+ 
          #          geom_point(aes(x=age,y=Ceq))+
          geom_point(aes(x=age,y=C-meanval, group = Type)))
  write.dta(plotdata,paste0(path,'modelSpending_bytype',suffix,'.dta'))
  
  plotdata<-regdata[selectC==1,mean(log(yearcons),trim=0),by=.(age,Health)]
  print(ggplot(data=plotdata)+ 
          geom_point(aes(x=age,y=V1,group=as.factor(Health),color=as.factor(Health))))
  write.dta(plotdata,paste0(path,'modelSpending_byhealth_spouse_',suffix,'.dta'))
  
  
  #PLOTS: PERMANENT WAGE:
  temp<-list(wagesetup_fit(newguess,0,0),wagesetup_lp(0,0), wagesetup_lp2(0,0))
  names<-c("","_lporig","_lp")
  for(it in 1){ 
    #for(it in 1:3){ 
    #PLOT WAGES ONCE FOR MY SETUP, ONCE FOR UPDATED LP
    Wage<-temp[[it]]$Wage
    wagepars<-temp[[it]]$wagepars
    spwagepars<-temp[[it]]$spwagepars
    paramvals<-newguess
    params<-paramsetup(newguess,wagepars,spwagepars)$params
    
    
    permwagedata<-data.table(age=23:62)
    permwagedata[,Wage_type1:=PermWage(age,wagepars,1)*params$hours]
    permwagedata[,Wage_type2:=PermWage(age,wagepars,2)*params$hours]
    permwagedata[,Wage_type3:=PermWage(age,wagepars,3)*params$hours]
    permwagedata[,spWage_type1:=PermWage(age,spwagepars,1)*params$hours]
    permwagedata[,spWage_type2:=PermWage(age,spwagepars,2)*params$hours]
    permwagedata[,spWage_type3:=PermWage(age,spwagepars,3)*params$hours]
    pdf(paste0(path,"permanentwage_byage",names[it],"_",suffix,".pdf"))
    print(ggplot(data=permwagedata) +
            # geom_hline(yintercept = paramvals[7]*params$hours*PermWage(23,wagepars,2), linetype='dashed') +
            #  geom_hline(yintercept = paramvals[8]*params$hours*PermWage(23,wagepars,2), linetype='dashed')+
            #  geom_hline(yintercept = paramvals[9]*params$hours*PermWage(23,spwagepars,2), linetype='dashed', color='red')+
            #  geom_hline(yintercept = paramvals[10]*params$hours*PermWage(23,spwagepars,2), linetype='dashed', color='red')+
            geom_line(aes(y=Wage_type1/1000,x=age,linetype='Head')) + geom_line(aes(y=Wage_type2/1000,x=age,linetype='Head'))  + geom_line(aes(y=Wage_type3/1000,x=age,linetype='Head'))+
            geom_line(aes(y=spWage_type1/1000,x=age,linetype='Partner')) +  geom_line(aes(y=spWage_type2/1000,x=age,linetype='Partner')) + geom_line(aes(y=spWage_type3/1000,x=age,linetype='Partner'))+
            #  geom_line(data=real_earnings, aes(y=fullearn,x=age,group=type_fix),linetype="dashed",size=1) +
            #  geom_line(data=real_earnings, aes(y=sp_fullearn,x=age,group=type_fix),linetype="dashed",color="red",size=1) +
            ylim(c(0,70))+
            labs(x="age",y="Earnings (full-time work, $1000)")+
            scale_linetype_manual(values=c("Head"="solid","Partner"="dashed"))+
            theme(axis.text=element_text(size=15,color="black"),
                  text= element_text(size=15,color='black'),
                  plot.title = element_text(size=15,color='black',hjust=0.5),
                  legend.title = element_blank())
          +mytheme +theme(legend.position = "bottom"))
    
    
    dev.off()
    
    # pdf(paste0("empiricalwage_byage",names[it],".pdf"))
    # print(ggplot(data=permwagedata) +
    #         # geom_hline(yintercept = paramvals[7]*params$hours*PermWage(23,wagepars,2), linetype='dashed') +
    #         #  geom_hline(yintercept = paramvals[8]*params$hours*PermWage(23,wagepars,2), linetype='dashed')+
    #         #  geom_hline(yintercept = paramvals[9]*params$hours*PermWage(23,spwagepars,2), linetype='dashed', color='red')+
    #         #  geom_hline(yintercept = paramvals[10]*params$hours*PermWage(23,spwagepars,2), linetype='dashed', color='red')+
    #         #geom_line(aes(y=Wage_type1,x=age)) + geom_line(aes(y=Wage_type2,x=age))  + geom_line(aes(y=Wage_type3,x=age))+
    #         #geom_line(aes(y=spWage_type1,x=age),color='red') +  geom_line(aes(y=spWage_type2,x=age),color='red') + geom_line(aes(y=spWage_type3,x=age),color='red')+
    #         geom_line(data=real_earnings, aes(y=fullearn/1000,x=age,group=type_fix),linetype="dashed",size=1) +
    #         geom_line(data=real_earnings, aes(y=sp_fullearn/1000,x=age,group=type_fix),linetype="dashed",color="red",size=1) +
    #         ylim(c(0,70))+
    #         labs(x="age",y="Earnings (full-time work, $1000)")+
    #         theme(axis.text=element_text(size=15,color="black"),
    #               text= element_text(size=15,color='black'),
    #               plot.title = element_text(size=15,color='black',hjust=0.5))
    #       +mytheme +theme(legend.position = "bottom"))
    # 
    # dev.off()
    
  }
  
}

#####Sensitivity analysis##########
plot_lambda<-function(Lambda, path, suffix, nocomp=FALSE,noflow=FALSE,noeventDI=TRUE,
                      nocontflow=TRUE, nostockDI=FALSE){
  wagevarnames<-c("Variance","Autocovariance","Spouse Variance","Spouse Autocovariance","Intra-Household Covariance")
  eventDInames <- c("DI after Moderate Shock","DI after Severe Shock")
  plotwagenames<-c("Low Type","Mid Type","High Type","Sev. Dis.","Mod. Dis.","Age","Age Sq.","Age \u2265 45","Age \u2265 45 and Sev. Dis.","Age \u2265 45 and Mod. Dis.")
  plotspwagenames<-c("Low Type","Mid Type","High Type","Disabled","Age","Age Sq.","Age \u2265 45","Age \u2265 45 and Disabled")
  plotconsnames_all<-c("Disability","Work","DI Receipt","Work X Disability","Spousal Disability","Spousal Work","Spousal Work X Disability")
  plotworknames<-c("Healthy, Age < 45","Healthy, Age \u2265 45","Mod. Dis., Age < 45", "Mod. Dis., Age \u2265 45","Sev. Dis., Age < 45","Sev. Dis., Age \u2265 45")
  plotspworknames <- c("Healthy, Age < 45","Healthy, Age \u2265 45", "Disabled, Age < 45", "Disabled, Age \u2265 45")
  plotcompDInames <- c("Sev. Dis., Age < 45","Sev. Dis., Age \u2265 45", "Mod. Dis., Age < 45","Mod. Dis., Age \u2265 45","Healthy, Age < 45","Healthy, Age \u2265 45",
                       "Sev. Dis., Age < 45","Sev. Dis., Age \u2265 45", "Mod. Dis., Age < 45","Mod. Dis., Age \u2265 45","Healthy, Age < 45","Healthy, Age \u2265 45")
  plotflowDInames <- c("Healthy, Age < 45","Healthy, Age \u2265 45","Mod. Dis., Age < 45","Mod. Dis., Age \u2265 45","Sev. Dis., Age < 45","Sev. Dis., Age \u2265 45",
                       "Healthy, Age < 45","Healthy, Age \u2265 45","Mod. Dis., Age < 45","Mod. Dis., Age \u2265 45","Sev. Dis., Age < 45","Sev. Dis., Age \u2265 45")
  
  Smat<-as.data.table(Lambda)
  Smat[,parameter:=rownames(Lambda)]
  Smat<-melt(Smat,id.vars="parameter")
  setnames(Smat,"variable","moment")
  
  momentnames<-c(plotwagenames,plotspwagenames,wagevarnames,plotconsnames_all,plotworknames,plotspworknames,plotcompDInames,eventDInames)
  
  Smat[,group:=c(rep("wagereg",length(plotwagenames)),
                 rep("spwagereg",length(plotspwagenames)),
                 rep("wagevse",length(wagevarnames)),
                 rep("cons",length(plotconsnames_all)),
                 rep("work",length(plotworknames)),
                 rep("spwork",length(plotspworknames)),
                 rep("compDI",length(plotcompDInames)/2),
                 rep("flowDI",length(plotcompDInames)/2),
                 rep("eventDI",length(eventDInames))
  ),by=parameter]
  
  Smat[parameter=="delta",parameterlab:="delta^1"]
  Smat[parameter=="eta",parameterlab:="eta^1"]
  Smat[parameter=="eta_sev",parameterlab:="eta^1,dis"]
  Smat[parameter=="theta_sev",parameterlab:="theta^1"]
  Smat[parameter=="F3",parameterlab:="F^1"]
  Smat[parameter=="spdelta",parameterlab:="delta^2"]
  Smat[parameter=="speta",parameterlab:="eta^2"]
  Smat[parameter=="speta_mod",parameterlab:="eta^2,dis"]
  Smat[parameter=="sptheta_mod",parameterlab:="theta^2"]
  Smat[parameter=="spF2",parameterlab:="F^2"]
  Smat[parameter=="pi0.young.married",parameterlab:="pi[0]^young"]
  Smat[parameter=="pi1.young.married",parameterlab:="pi[1]^young"]
  Smat[parameter=="pi2.young.married",parameterlab:="pi[2]^young"]
  Smat[parameter=="pi0.old.married",parameterlab:="pi[0]^old"]
  Smat[parameter=="pi1.old.married",parameterlab:="pi[1]^old"]
  Smat[parameter=="pi2.old.married",parameterlab:="pi[2]^old"]
  Smat[group=="eventDI",grouplab:="Event \n Study"]
  Smat[group=="flowDI",grouplab:="DI Entry"]
  Smat[group=="compDI",grouplab:="Share of \n DI Rolls"]
  Smat[group=="work",grouplab:="Employment"]
  Smat[group=="spwork",grouplab:="Spousal \n Work"]
  Smat[group=="wagereg",grouplab:="Wage \n Regression"]
  Smat[group=="spwagereg",grouplab:="Spousal Wage \n Regression"]
  Smat[group=="wagevse",grouplab:="Wage \n Variation"]
  Smat[group=="cons",grouplab:="Consumption \n Regression"]
  # Smat[group=="eventDI",grouplab:="Event~\n~Study"]
  # Smat[group=="flowDI",grouplab:="DI~Entry"]
  # Smat[group=="compDI",grouplab:="Share~of~\n~DI~Rolls"]
  # Smat[group=="work",grouplab:="Work"]
  # Smat[group=="spwork",grouplab:="Spousal~\n~Work"]
  # Smat[group=="wagereg",grouplab:="Wage~\n~Regression"]
  # Smat[group=="spwagereg",grouplab:="Spousal~Wage~\n~Regression"]
  # Smat[group=="wagevse",grouplab:="Wage~\n~Variation"]
  # Smat[group=="cons",grouplab:="Consumption~\n~Regression"]
   
  
  Smat[moment=="Spousal Work X Disability",moment:="Spousal Work \n X Disability"]
  
  # png(paste0(path,"sensitivity_prefs_",suffix,".png"))
  # print(ggplot(data=Smat[parameter%in%c("eta","eta_sev","theta_sev"#,"F3","delta"
  #                                       ) &
  #                          group%in%c("cons","work"),])+
  #         geom_col(aes(y=value,x=moment))+
  #         labs(x="Moment",y="Sensitivity")+
  #         geom_hline(yintercept=0,linetype="dashed")+
  #         coord_flip()+
  #         facet_grid(cols=vars(parameterlab),rows=vars(grouplab), scales="free", space="free", switch="y",
  #                    labeller = label_parsed
  #                    #labeller=labeller(group=grouplabs)
  #         )+
  #         theme(strip.text.y=element_text(size=18, angle=270),
  #               strip.background = element_blank(),
  #               axis.title.x = element_text(size=18),
  #               axis.title.y = element_text(size=18),
  #               axis.text.x = element_text(size=18),
  #               axis.text.y = element_text(size=18),
  #               strip.placement="outside")
  # )
  # dev.off()
  # 
  
  # png(paste0(path,"sensitivity_prefs_work_",suffix,".png"))
  # print(ggplot(data=Smat[parameter%in%c("eta","eta_sev","theta_sev"#,"F3","delta"
  # ) &
  #   group%in%c("work"),])+
  #   geom_point(aes(y=value,x=moment))+
  #   labs(x="Employment Rate",y="Change in Parameter per Change in Moment")+
  #   geom_hline(yintercept=0,linetype="dashed")+
  #   coord_flip()+
  #   facet_grid(cols=vars(parameterlab), scales="free", space="fixed",
  #              switch="y",
  #              labeller = label_parsed
  #              #labeller=labeller(group=grouplabs)
  #   )+
  #   theme(strip.text.y=element_text(size=18, angle=270),
  #         strip.background = element_blank(),
  #         axis.title.x = element_text(size=18),
  #         axis.title.y = element_text(size=18),
  #         axis.text.x = element_text(size=18),
  #         axis.text.y = element_text(size=18),
  #         strip.placement="outside")
  # )
  # dev.off()
  Smat[,fill:=abs(value)/max(abs(value)),by=.(grouplab,parameterlab)]
  
  cairo_pdf(paste0(path,"sensitivity_prefsall_",suffix,".pdf"),width=12)
  print(ggplot(data=Smat[parameter%in%c("eta","eta_sev","theta_sev","F3","delta",
                                        "speta","speta_mod","sptheta","spdelta","spF2")
#        & !grepl("Spousal",moment) 
    & group%in%c("work","spwork","cons"),])+
    geom_tile(aes(y=factor(parameterlab,levels=c("eta^1","eta^1,dis","theta^1","F^1","delta^1",
                                                 "eta^2","eta^2,dis","theta^2","F^2","delta^2")),
                  x=moment,fill=as.factor(abs(fill))))+
    geom_text(aes(y=parameterlab,x=moment,label=formatC(value,digits=2,format="f")),size=6)+
    scale_fill_grey(start=0.9,end=0.4) +
    labs(x="Moment",y="Parameter")+
    scale_y_discrete(labels=expression(eta^1,eta^paste(1,",",dis),theta^1,F^1,delta^1,
                                       eta^2,eta^paste(2,",",dis),theta^2,F^2,delta^2))+
    coord_flip()+
    facet_grid(rows=vars(grouplab), scales="free", space="free",
               switch="y"
               #labeller=labeller(group=grouplabs)
    )+
    theme(strip.text.y=element_text(size=18, angle=270),
          strip.background = element_blank(),
          axis.title.x = element_text(size=18),
          axis.title.y = element_text(size=18),
          axis.text.x = element_text(size=18),
          axis.text.y = element_text(size=18),
          strip.placement="outside")+
    theme(legend.position="none")
  )
  dev.off()
  
  cairo_pdf(paste0(path,"sensitivity_prefs_",suffix,".pdf"))
  print(ggplot(data=Smat[parameter%in%c("eta","eta_sev","theta_sev","F3","delta")
                         & !grepl("Spousal",moment) 
                         & group%in%c("work","cons"),])+
          geom_tile(aes(y=factor(parameterlab,levels=c("eta^1","eta^1,dis","theta^1","F^1","delta^1")),
                        x=moment,fill=as.factor(abs(fill))))+
          geom_text(aes(y=parameterlab,x=moment,label=formatC(value,digits=2,format="f")),size=6)+
          scale_fill_grey(start=0.9,end=0.4) +
          labs(x="Moment",y="Parameter")+
          scale_y_discrete(labels=expression(eta^1,eta^paste(1,",",dis),theta^1,F^1,delta^1))+
          coord_flip()+
          facet_grid(rows=vars(grouplab), scales="free", space="free",
                     switch="y"
                     #labeller=labeller(group=grouplabs)
          )+
          theme(strip.text.y=element_text(size=18, angle=270),
                strip.background = element_blank(),
                axis.title.x = element_text(size=18),
                axis.title.y = element_text(size=18),
                axis.text.x = element_text(size=18),
                axis.text.y = element_text(size=18),
                strip.placement="outside")+
          theme(legend.position="none")
  )
  dev.off()
  
  cairo_pdf(paste0(path,"sensitivity_wages_",suffix,".pdf"),width=12)
  print(ggplot(data=Smat[parameter%in%c("age","age2","mod","sev","Type1","Type2","Type3","noisevar","wagevar")
                         & !grepl("Spouse",moment) 
                         & !grepl("Intra-",moment) 
                         & group%in%c("wagereg","wagevse"),])+
          geom_tile(aes(y=factor(parameter,levels=c("Type1","Type2","Type3","age","age2","mod","sev","noisevar",
                                                    "wagevar")),
                        x=moment,fill=as.factor(abs(fill))))+
          geom_text(aes(y=parameter,x=moment,label=formatC(value,digits=2,format="f")),size=6)+
          scale_fill_grey(start=0.9,end=0.4) +
          labs(x="Moment",y="Parameter")+
          scale_y_discrete(labels=expression(f[1],f[2],f[3],Age,Age^2,H^{mod},H^{sev},sigma[epsilon],sigma[xi],rho[xi]))+
          coord_flip()+
          facet_grid(rows=vars(grouplab), scales="free", space="free",
                     switch="y"
                     #labeller=labeller(group=grouplabs)
          )+
          theme(strip.text.y=element_text(size=18, angle=270),
                strip.background = element_blank(),
                axis.title.x = element_text(size=18),
                axis.title.y = element_text(size=18),
                axis.text.x = element_text(size=18),
                axis.text.y = element_text(size=18),
                strip.placement="outside")+
          theme(legend.position="none")
  )
  dev.off()
  
  
  cairo_pdf(paste0(path,"sensitivity_prefs_work_",suffix,".pdf"))
  print(ggplot(data=Smat[parameter%in%c("eta","eta_sev","theta_sev","F3","delta"
  ) &
    group%in%c("work"),])+
    geom_tile(aes(y=factor(parameterlab,levels=c("eta^1","eta^1,dis","theta^1","F^1","delta^1")),
                  x=moment,fill=as.factor(abs(fill))))+
    geom_text(aes(y=parameterlab,x=moment,label=formatC(value,digits=2,format="f")),size=6)+
    scale_fill_grey(start=0.9,end=0.4) +
    labs(x="Moment",y="Parameter")+
    scale_y_discrete(labels=expression(eta^1,eta^paste(1,",",dis),theta^1,F^1,delta^1))+
    coord_flip()+
    theme(strip.text.y=element_text(size=18, angle=270),
          strip.background = element_blank(),
          axis.title.x = element_text(size=18),
          axis.title.y = element_text(size=18),
          axis.text.x = element_text(size=18),
          axis.text.y = element_text(size=18),
          strip.placement="outside")+
    theme(legend.position="none")
  )
  dev.off()
  
  
  cairo_pdf(paste0(path,"sensitivity_prefs_cons_",suffix,".pdf"))
  print(ggplot(data=Smat[parameter%in%c("eta","eta_sev","theta_sev","F3","delta"
  ) &
    group%in%c("cons"),])+
    geom_tile(aes(y=factor(parameterlab,levels=c("eta^1","eta^1,dis","theta^1","F^1","delta^1")),
                  x=moment,fill=as.factor(abs(fill))))+
    geom_text(aes(y=parameterlab,x=moment,label=formatC(value,digits=2,format="f")),size=6)+
    scale_fill_grey(start=0.9,end=0.4) +
    labs(x="Moment",y="Parameter")+
    scale_y_discrete(labels=expression(eta^1,eta^paste(1,",",dis),theta^1,F^1,delta^1))+
    coord_flip()+
    theme(strip.text.y=element_text(size=18, angle=270),
          strip.background = element_blank(),
          axis.title.x = element_text(size=18),
          axis.title.y = element_text(size=18),
          axis.text.x = element_text(size=18),
          axis.text.y = element_text(size=18),
          strip.placement="outside")+
    theme(legend.position="none")
  )
  dev.off()
  

  cairo_pdf(paste0(path,"sensitivity_allowance_",suffix,".pdf"),width=9)
  print(ggplot(data=Smat[parameter%in%c("pi0.young.married","pi1.young.married","pi2.young.married",
                                        "pi0.old.married","pi1.old.married","pi2.old.married")
                         & group%in%c("compDI","eventDI"),])+
          geom_tile(aes(y=factor(parameterlab,levels=c("pi[0]^young","pi[1]^young","pi[2]^young",
                                                       "pi[0]^old","pi[1]^old","pi[2]^old")),
                        x=moment,fill=as.factor(abs(fill))))+
          geom_text(aes(y=parameterlab,x=moment,label=formatC(value,digits=2,format="f")),size=6)+
          scale_fill_grey(start=0.9,end=0.4) +
          labs(x="Moment",y="Parameter")+
          scale_y_discrete(labels=expression(pi[0]^young,pi[1]^young,pi[2]^young,
                                             pi[0]^old,pi[1]^old,pi[2]^old))+
          geom_hline(yintercept=0,linetype="dashed")+
          coord_flip()+
          facet_grid(rows=vars(grouplab), scales="free", space="free", switch="y"
                     #labeller=labeller(group=grouplabs)
          )+
          theme(strip.text.y=element_text(size=18, angle=270),
                strip.background = element_blank(),
                axis.title.x = element_text(size=18),
                axis.title.y = element_text(size=18),
                axis.text.x = element_text(size=18),
                axis.text.y = element_text(size=18),
                strip.placement="outside")+
          theme(legend.position="none")
  )
  dev.off()
  
  # png(paste0(path,"sensitivity_allowance_young_",suffix,".png"))
  # print(ggplot(data=Smat[parameter%in%c("pi0.young.married","pi1.young.married","pi2.young.married") 
  #                        & group%in%c("compDI","eventDI", "flowDI")
  #                        ,])+
  #         geom_point(aes(y=value,x=moment))+
  #         labs(x="Moment",y="Change in Parameter per Change in Moment")+
  #         geom_hline(yintercept=0,linetype="dashed")+
  #         coord_flip()+
  #         facet_grid(cols=vars(parameterlab),rows=vars(grouplab), scales="free", space="free", switch="y",
  #                    labeller = label_parsed
  #                    #labeller=labeller(group=grouplabs)
  #         )+
  #         theme(strip.text.y=element_text(size=18, angle=270),
  #               strip.background = element_blank(),
  #               axis.title.x = element_text(size=18),
  #               axis.title.y = element_text(size=18),
  #               axis.text.x = element_text(size=18),
  #               axis.text.y = element_text(size=18),
  #               strip.placement="outside")
  # )
  # dev.off()
  # 
  # 
  # png(paste0(path,"sensitivity_allowance_old_",suffix,".png"))
  # print(ggplot(data=Smat[parameter%in%c("pi0.old.married","pi1.old.married","pi2.old.married") 
  #                        & group%in%c("compDI","eventDI","flowDI"),])+
  #         geom_point(aes(y=value,x=moment))+
  #         labs(x="Moment",y="Change in Parameter per Change in Moment")+
  #         geom_hline(yintercept=0,linetype="dashed")+
  #         coord_flip()+
  #         facet_grid(cols=vars(parameter),rows=vars(grouplab), scales="free", space="free", switch="y"
  #                    #labeller=labeller(group=grouplabs)
  #         )+
  #         theme(strip.text.y=element_text(size=14, angle=270),
  #               strip.background = element_blank(),
  #               axis.title.x = element_text(size=14),
  #               axis.title.y = element_text(size=14),
  #               axis.text.x = element_text(size=12),
  #               axis.text.y = element_text(size=12),
  #               strip.placement="outside")
  # )
  # dev.off()
  
}












##########################
####EVENT STUDY CODE######



evalevent<-function(simdata,path,suffix,onlysingle=FALSE,onlymarried=FALSE,onlyFT=FALSE, eventtype="head"){
  if(eventtype=='enterDI'){
    regdata<-copy(simdata[Health>1,])
    regdata[time+23<=62,everevent:=max(DI==2),by=.(i,Type)]
    regdata[,anyeventage=min(age+9999*(DI!=2)),by=.(i,Type)]
    regdata[,eventage=min(age+9999*(DI!=2)),by=.(i,Type)]
  }   else {
    regdata<-copy(simdata)
    regdata[,everevent:=max((Health!=1|spHealth!=2)&select==1),by=.(i,Type)]
    regdata[,anyeventage:=min(age+9999*(Health==1)*(spHealth==1)+9999*(select!=1)),by=.(i,Type)]
    regdata[anyeventage>=9999,anyeventage:=Inf]
    if(eventtype=='headsev') {
      regdata[,eventage:=min(age+9999*(Health==1)+9999*(spHealth!=1) +9999*(select!=1)),by=.(i,Type)]
      regdata[,eventage1:=min(age+9999*(Health!=3)+9999*(spHealth!=1) +9999*(select!=1)),by=.(i,Type)]
      #A moderate condition must become severe within 5 years:
      regdata[eventage1>=eventage+5,eventage:=Inf]
      regdata[,eventage1:=NULL]
    }
    if(eventtype=='headmod') regdata[,eventage:=min(age+9999*(Health!=2)+9999*(spHealth!=1) +9999*(select!=1)),by=.(i,Type)]
    if(eventtype=='head') regdata[,eventage:=min(age+9999*(Health==1)+9999*(spHealth!=1) +9999*(select!=1)),by=.(i,Type)]
    if(eventtype=='both') regdata[,eventage:=min(age+9999*(Health*spHealth==1)+9999*(select!=1)),by=.(i,Type)]
    #Killing guys who never get event, or have a spouse who gets it first/jointly
  }
  regdata[eventage>=9999,eventage:=Inf]
  regdata[,empyet:=cumsum(select * Work)>=1,by=.(i,Type)]
  regdata[,empyet:=as.double(empyet)]
  regdata[,marnow:=as.double(single==0)]
  regdata[,marnow1:=c(marnow[-1],NA),by=.(i,Type)]
  regdata[is.na(marnow1),marnow1:=marnow]
  regdata[,marnow:=marnow1]
  regdata[,marnow1:=NULL]
  regdata[,hours:=Work*params$hours]
  regdata[,sp_hours:=spWork*params$hours]
  
  regdata[,logC:=log(Ceq)]
  
  regdata[,time:=NULL]
  
  if(onlysingle == TRUE) vars<- c("yearDI","Work","Workpart","spWork","spWorkpart","Ceq", "logC","empWage","spempWage")
  else if(onlymarried==TRUE) vars<- c("yearDI","Work","Workpart","spWork","spWorkpart","Ceq", "logC","empWage","spempWage")
  else vars<- c("yearDI","Work","hours","sp_hours","spWork","spWorkpart")
  if(onlyFT==TRUE) vars<-vars[!grepl("part",vars)]

  if(onlysingle==1) {
    regdata[,empyetmarnow:=as.double(empyet * (marnow==0))]
    eventdata<- create_event_data(regdata[select==1,],
                                  timevar = "age", unitvar="i",
                                  cohortvar = "eventage", anycohortvar = "anyeventage",
                                  lower_event_time=-6,
                                  upper_event_time=6,
                                  base_restrict = "empyetmarnow",
                                  covariate_base_balance = 1)
    results<-event_ATTs(eventdata,outcomes=vars)
    eventdata_chunk<-copy(eventdata)
    eventdata_chunk[as.numeric(as.character(event_time))>0 & as.numeric(as.character(event_time)) <= 1,event_time:="0"]
    eventdata_chunk[as.numeric(as.character(event_time))>1 ,event_time:="1"]
    results_chunk<-event_ATTs(eventdata_chunk,outcomes=vars)
    
    
    eventdata<- create_event_data(regdata[selectC==1,],
                                  timevar = "age", unitvar="i",
                                  cohortvar = "eventage", anycohortvar = "anyeventage",
                                  base_time = -2,
                                  lower_event_time=-6,
                                  upper_event_time=6,
                                  base_restrict = "empyetmarnow",
                                  covariate_base_balance = 1)
    results_cons<-event_ATTs(eventdata,outcomes="logC")    
    eventdata_chunk<-copy(eventdata)
    eventdata_chunk[as.numeric(as.character(event_time))>0 & as.numeric(as.character(event_time)) <= 1,event_time:="0"]
    eventdata_chunk[as.numeric(as.character(event_time))>1 ,event_time:="1"]
    results_cons_chunk<-event_ATTs(eventdata_chunk,outcomes=c("logC","Asset"))
  }
  else if(onlymarried==1) {
    regdata[,empyetmarnow:=as.double(empyet * (marnow==1))]
    eventdata<- create_event_data(regdata[select==1,],
                                  timevar = "age", unitvar="i",
                                  cohortvar = "eventage", anycohortvar = "anyeventage",
                                  lower_event_time=-6,
                                  upper_event_time=6,
                                  base_restrict = "empyetmarnow",
                                  covariate_base_balance = 1)
    results<-event_ATTs(eventdata,outcomes=vars)
    eventdata_chunk<-copy(eventdata)
    eventdata_chunk[as.numeric(as.character(event_time))>0 & as.numeric(as.character(event_time)) <= 1,event_time:="0"]
    eventdata_chunk[as.numeric(as.character(event_time))>1 ,event_time:="1"]
    results_chunk<-event_ATTs(eventdata_chunk,outcomes=vars)
    
    
    eventdata<- create_event_data(regdata[selectC==1,],
                                  timevar = "age", unitvar="i",
                                  cohortvar = "eventage", anycohortvar = "anyeventage",
                                  base_time = -2,
                                  lower_event_time=-6,
                                  upper_event_time=6,
                                  base_restrict = "empyetmarnow",
                                  covariate_base_balance = 1)
    results_cons<-event_ATTs(eventdata,outcomes="logC")
    eventdata_chunk<-copy(eventdata)
    eventdata_chunk[as.numeric(as.character(event_time))>0 & as.numeric(as.character(event_time)) <= 1,event_time:="0"]
    eventdata_chunk[as.numeric(as.character(event_time))>1 ,event_time:="1"]
    results_cons_chunk<-event_ATTs(eventdata_chunk,outcomes=c("logC","Asset"))
    
  }
  else {
  eventdata<- create_event_data(regdata[select==1,],
                                timevar = "age", unitvar="i",
                                cohortvar = "eventage", anycohortvar = "anyeventage",
                                lower_event_time=-6,
                                upper_event_time=6,
                                base_restrict = "empyet",
                                covariate_base_stratify="marnow",
                                covariate_base_balance = 1)
  results<-event_ATTs(eventdata,outcomes=vars)
  eventdata_nowsev<- create_event_data(regdata[select==1 & (age < eventage | Health==3),],
                                       timevar = "age", unitvar="i",
                                       cohortvar = "eventage", anycohortvar = "anyeventage",
                                       lower_event_time=-6,
                                       upper_event_time=6,
                                       base_restrict = "empyet",
                                       covariate_base_stratify="marnow",
                                       covariate_base_balance = 1)
  results_nowsev<-event_ATTs(eventdata_nowsev,outcomes=vars)
  eventdata_notsev<- create_event_data(regdata[select==1 & (age < eventage | Health!=3),],
                                       timevar = "age", unitvar="i",
                                       cohortvar = "eventage", anycohortvar = "anyeventage",
                                       lower_event_time=-6,
                                       upper_event_time=6,
                                       base_restrict = "empyet",
                                       covariate_base_stratify="marnow",
                                       covariate_base_balance = 1)
  results_notsev<-event_ATTs(eventdata_notsev,outcomes=vars)
  
  eventdata_chunk<-copy(eventdata)
  eventdata_chunk[as.numeric(as.character(event_time))>0 & as.numeric(as.character(event_time)) <= 1,event_time:="0"]
  eventdata_chunk[as.numeric(as.character(event_time))>1 ,event_time:="1"]
  results_chunk<-event_ATTs(eventdata_chunk,outcomes=vars)
  
  eventdata<- create_event_data(regdata[selectC==1,],
                                timevar = "age", unitvar="i",
                                cohortvar = "eventage", anycohortvar = "anyeventage",
                                base_time = -2,
                                lower_event_time=-6,
                                upper_event_time=6,
                                base_restrict = "empyet",
                                covariate_base_stratify="marnow",
                                covariate_base_balance = 1)
  
  eventdata_nowsev<- create_event_data(regdata[selectC==1 & (age < eventage | Health==3),],
                                timevar = "age", unitvar="i",
                                cohortvar = "eventage", anycohortvar = "anyeventage",
                                base_time = -2,
                                lower_event_time=-6,
                                upper_event_time=6,
                                base_restrict = "empyet",
                                covariate_base_stratify="marnow",
                                covariate_base_balance = 1)
  eventdata_notsev<- create_event_data(regdata[selectC==1 & (age < eventage | Health!=3),],
                                       timevar = "age", unitvar="i",
                                       cohortvar = "eventage", anycohortvar = "anyeventage",
                                       base_time = -2,
                                       lower_event_time=-6,
                                       upper_event_time=6,
                                       base_restrict = "empyet",
                                       covariate_base_stratify="marnow",
                                       covariate_base_balance = 1)
  
  results_cons<-event_ATTs(eventdata,outcomes=c("logC","Asset"))
  results_cons_nowsev<-event_ATTs(eventdata_nowsev,outcomes=c("logC","Asset"))
  results_cons_notsev<-event_ATTs(eventdata_notsev,outcomes=c("logC","Asset"))
  eventdata_chunk<-copy(eventdata)
  eventdata_chunk[as.numeric(as.character(event_time))>0 & as.numeric(as.character(event_time)) <= 1,event_time:="0"]
  eventdata_chunk[as.numeric(as.character(event_time))>1 ,event_time:="1"]
  results_cons_chunk<-event_ATTs(eventdata_chunk,outcomes=c("logC","Asset"))
  }
    

    
  
  rformcoeftable<-data.table(married=c(0,1))
  if(onlymarried ==1) ms<-1
  else if(onlysingle == 1) ms <-0
  else ms <- 0:1

  for(m in ms){
    for(v in c(vars) ){
      #  for (o in unique(eventdata[get(keepvar)==1&get(selectvar)==1, eventage])) {
      #    eventreg<-lm(get(var)~ as.factor(eventtime)+as.factor(treated)+treatint,weights=get(weightvar),data=eventdata[eventage==o&get(selectvar)==1&get(keepvar)==1,])
        coef<-results[["pooled"]][[which(names(results[["pooled"]])==paste0("lhs: ",v))]][["coeftable"]][paste0("treated_post_stratify1.",m),"Estimate"]
        if(is.na(coef)) coef<-0
        rformcoeftable[married==m,eval(v):=coef] 

      #  }
        
    }
    coef<-results_cons[["pooled"]][[which(names(results_cons[["pooled"]])=="lhs: logC")]][["coeftable"]][paste0("treated_post_stratify1.",m),"Estimate"]
    if(is.na(coef)) coef<-0
    rformcoeftable[married==m,logC:=coef] 
    
  }
  
  
  
  rformcoeftable<-rbind(rformcoeftable,rformcoeftable[2,]-rformcoeftable[1,])
  rformcoeftable[3,married:=NA]
  
  if(eventtype == "headsev") {
    rform_events<-as.data.table(read.csv("./eventstudy/PSID_eventstudy/headsev_pooled_table.csv"))
    rform_events_nowsev<-as.data.table(read.csv("./eventstudy/PSID_eventstudy/headsev_nowsev_pooled_table.csv"))
    rform_events_notsev<-as.data.table(read.csv("./eventstudy/PSID_eventstudy/headsev_notsev_pooled_table.csv"))
    #rform_events<-as.data.table(read.csv("rform_eventstudies_pooled_headsev.csv"))
  }
  if(eventtype == "headmod") {
    rform_events<-as.data.table(read.csv("./eventstudy/PSID_eventstudy/headmod_pooled_table.csv"))
    #rform_events<-as.data.table(read.csv("rform_eventstudies_pooled_headmod.csv"))
  }
  if(eventtype == "head") {
    rform_events<-as.data.table(read.csv("./eventstudy/PSID_eventstudy/head_pooled_table.csv"))
    #rform_events <- as.data.table(read.csv("rform_eventstudies_pooled_head.csv"))
  }
  varnames<-rform_events[,X]
  cleanrform<-function(rform_events){
  rform_events[,X:=NULL]
  rform_events$V1<-as.numeric(as.character(rform_events$V1))
  rform_events$V2<-as.numeric(as.character(rform_events$V2))
  rform_events<-t(rform_events)
  colnames(rform_events)<-varnames
  rform_events<-cbind(coef=c("b","se"),rform_events)
  rform_events<-as.data.table(rform_events)
  rform_events<-reshape(rform_events,direction="long",varying=names(rform_events)[-1],sep="_m",timevar="group")
  return(rform_events)
  }
  rform_events_main<-copy(rform_events)
  rform_events<-cleanrform(rform_events)
  setnames(rform_events_main,c("X","V1","V2"),c("var","b","se"))
  rform_events_main[grepl("_m1",var),married:=1]
  rform_events_main[grepl("_m0",var),married:=0]
  rform_events_main[,var:=gsub("_m.","",var)]
  

  setnames(rform_events_nowsev,c("X","V1","V2"),c("var","b","se"))
  rform_events_nowsev[grepl("_m1",var),married:=1]
  rform_events_nowsev[grepl("_m0",var),married:=0]
  rform_events_nowsev[,var:=gsub("_m.","",var)]
  setnames(rform_events_notsev,c("X","V1","V2"),c("var","b","se"))
  rform_events_notsev[grepl("_m1",var),married:=1]
  rform_events_notsev[grepl("_m0",var),married:=0]
  rform_events_notsev[,var:=gsub("_m.","",var)]
  
  
  if(onlysingle==1) {
    keepcols<-c('married',"yearDI",'Work','Workpart','Spending',"hours","sp_hours")
    oldcols<-c('group',"anyDI","emp","emppart","logspending_eq","hours","sp_hours")
  }
  else if(onlymarried==1) {
    keepcols<-c('married',"yearDI",'spWork','spWorkpart','Work','Workpart','Spending',"hours","sp_hours")
    oldcols<-c('group',"anyDI","empspouse","empspousepart","emp","emppart","logspending_eq","hours","sp_hours")
  }
  else {
    keepcols<-c('married',"yearDI",'spWork','spWorkpart','Work','Workpart','Spending',"hours","sp_hours")
    oldcols<-c('group',"anyDI","empspouse","empspousepart","emp","emppart","logspending_eq","hours","sp_hours")
  }
  if(onlyFT==1) {
    keepcols<-keepcols[!grepl("part",keepcols)]
    oldcols<-oldcols[!grepl("part",oldcols)]
  }
  setnames(rform_events,old=oldcols,new=keepcols)
  setnames(rformcoeftable,old=c("logC"),new="Spending")
  rform_se<-rform_events[coef=="se",]
  rform_se<-rform_se[,coef:=NULL]
  rform_events<-rform_events[coef=="b",]
  rform_events<-rform_events[,coef:=NULL]
  
  setcolorder(rform_events,keepcols)
  setcolorder(rform_se,keepcols)
  setcolorder(rformcoeftable,keepcols)
  
  #Latex table
  eventoutcomes<-c("yearDI","hours","sp_hours", "logC")
  eventoutcomes_rform<-c("anyDI","hours","sp_hours", "logspending_eq")
  eventnames<-c("DI Receipt","Work Hours","Spouse Work Hours","Log Spending")
  eventable<-TR(c("","Single","Married"),cspan=c(1,4,4))+
    TR(c("","Data","Simulation","Diff","St. Error","Data","Simulation","Diff","St. Error"))+
    midrulep(list(c(2,5),c(6,9)))
  
  for(outnum in 1:length(eventoutcomes)){
    if(paste0("lhs: ",eventoutcomes[outnum])%in%c(names(results$pooled))) resultvals <-results
    else resultvals <-results_cons
    outpos<-which(names(resultvals$dynamic) == paste0("lhs: ",eventoutcomes[outnum]))
  
  ######EVENT STUDY, CONDITIONING ON CURRENT HEALTH:
  eventable<-TR(c("","Single","Married"),cspan=c(1,4,4))+
    TR(c("","","","Data - Simulation","","","Data - Simulation"),cspan=c(1,1,1,2,1,1,2))+
    TR(c("","Data","Simulation","Coef.","St. Error","Data","Simulation","Coef.","St. Error"))+
    midrulep(list(c(2,5),c(6,9)))+
    TR("Panel A: Effects for Current Severely-Limited Households",surround = "\\textit{%s}",cspan=c(9))
  for(outnum in 1:length(eventoutcomes)){
    if(paste0("lhs: ",eventoutcomes[outnum])%in%c(names(results_chunk$pooled))) resultvals <-results_nowsev
    else resultvals <-results_cons_nowsev
    outpos<-which(names(resultvals$dynamic) == paste0("lhs: ",eventoutcomes[outnum]))
    eventable<-eventable+TR(eventnames[outnum])%:%TR(c(as.numeric(rform_events_nowsev[married==0 &var==eventoutcomes_rform[outnum],b]),
                                                       resultvals[["pooled"]][[outpos]]$coefficients["treated_post_stratify1.0"]),dec=2)%:%
      TR(c(resultvals[["pooled"]][[outpos]]$coefficients["treated_post_stratify1.0"] -as.numeric(rform_events_nowsev[married==0 &var==eventoutcomes_rform[outnum],b])),
         dec=2, pvalues = myp(-abs(resultvals[["pooled"]][[outpos]]$coefficients["treated_post_stratify1.0"] -as.numeric(rform_events_nowsev[married==0 &var==eventoutcomes_rform[outnum],b]))/simse(rform_events_nowsev[married==0 & var==eventoutcomes_rform[outnum],se])))%:%
      TR(c(rform_events_nowsev[married==0 & var==eventoutcomes_rform[outnum],se]),dec=2,se=TRUE)%:%
      TR(c(as.numeric(rform_events_nowsev[married==1 & var==eventoutcomes_rform[outnum],b]),
           resultvals[["pooled"]][[outpos]]$coefficients["treated_post_stratify1.1"]),dec=2)%:%
      TR(c(resultvals[["pooled"]][[outpos]]$coefficients["treated_post_stratify1.1"] -as.numeric(rform_events_nowsev[married==1 &var==eventoutcomes_rform[outnum],b])),
         dec=2, pvalues = myp(-abs(resultvals[["pooled"]][[outpos]]$coefficients["treated_post_stratify1.1"] - as.numeric(rform_events_nowsev[married==1 &var==eventoutcomes_rform[outnum],b]))/simse(rform_events_nowsev[married==1 & var==eventoutcomes_rform[outnum],se])))%:%
      TR(c(rform_events_nowsev[married==1 &var==eventoutcomes_rform[outnum],se]),dec=2,se=TRUE)    
  }
  
  eventable<- eventable+vspace(5)+
    TR("Panel B: Effects for Recovered Households",surround = "\\textit{%s}",cspan=c(9))
  for(outnum in 1:length(eventoutcomes)){
    if(paste0("lhs: ",eventoutcomes[outnum])%in%c(names(results_chunk$pooled))) resultvals <-results_notsev
    else resultvals <-results_cons_notsev
    outpos<-which(names(resultvals$dynamic) == paste0("lhs: ",eventoutcomes[outnum]))
    eventable<-eventable+TR(eventnames[outnum])%:%TR(c(as.numeric(rform_events_notsev[married==0 & var==eventoutcomes_rform[outnum],b]),
                                                       resultvals[["pooled"]][[outpos]]$coefficients["treated_post_stratify1.0"]),dec=2)%:%
      TR(c(resultvals[["pooled"]][[outpos]]$coefficients["treated_post_stratify1.0"] -as.numeric(rform_events_notsev[married==0 &var==eventoutcomes_rform[outnum],b])),
         dec=2, pvalues = myp(-abs(resultvals[["pooled"]][[outpos]]$coefficients["treated_post_stratify1.0"] -as.numeric(rform_events_notsev[married==0 &var==eventoutcomes_rform[outnum],b]))/simse(rform_events_notsev[married==0 &var==eventoutcomes_rform[outnum],se])))%:%
      TR(rform_events_notsev[married==0 & var==eventoutcomes_rform[outnum],se],dec=2,se=TRUE)%:%
      TR(c(as.numeric(rform_events_notsev[married==1 &var==eventoutcomes_rform[outnum],b]),
           resultvals[["pooled"]][[outpos]]$coefficients["treated_post_stratify1.1"]),dec=2)%:%
      TR(c(resultvals[["pooled"]][[outpos]]$coefficients["treated_post_stratify1.1"] -as.numeric(rform_events_notsev[married==1 & var==eventoutcomes_rform[outnum],b])),
         dec=2, pvalues = myp(-abs(resultvals[["pooled"]][[outpos]]$coefficients["treated_post_stratify1.1"] -as.numeric(rform_events_notsev[married==1 & var==eventoutcomes_rform[outnum],b]))/simse(rform_events_notsev[married==1 & var==eventoutcomes_rform[outnum],se])))%:%
      TR(rform_events_notsev[married==1 & var==eventoutcomes_rform[outnum],se],dec=2,se=TRUE)
  }
  
  saveRDS(eventable,file=paste0(path,"/eventstudy",eventtype,"_sim_healthresults_",suffix,".RDS"))
  
  
  ###PRINT COEFTABLE VALUES, CHECK THAT THEY ARE CONSTRUCTED SAME WAY IN STATA:
  marnames <-c("single","married")
  for(m in ms){
    eventplot<-as.data.table(cbind(t(rformcoeftable[married==m,keepcols,with=FALSE]),t(rform_events[married==m,keepcols,with=FALSE]),
                                   simse(as.numeric(rform_se[married==m,keepcols,with=FALSE]))))
    names(eventplot)<-c('Simulation','Data',"SE")
    eventplot<-eventplot[-1,]
    eventplot[,outcome:=keepcols[-1]]
    
    eventplot[outcome=="yearDI",outcome:="DI Receipt"]
    eventplot[outcome=="empWage",outcome:="Head Earnings"]
    eventplot[outcome=="spempWage",outcome:="Spousal Earnings"]
    eventplot[outcome=="spWork",outcome:="Spouse Work"]
    eventplot[outcome=="Spending",outcome:="Log Spending"]
    
    pdf(paste0(path,'eventstudy',eventtype,'_sim_binary',marnames[m+1],'_',suffix,'.pdf'))
    print(ggplot(data=eventplot[outcome%in%c('Spouse Work','Work','DI Receipt','Log Spending'),])+
            geom_point(aes(x=outcome,y=as.numeric(Data),shape="Data"),size=4)
          +geom_point(aes(x=outcome,y=as.numeric(Simulation),shape="Simulation"),size=4)
          +geom_errorbar(aes(x=outcome, ymin = as.numeric(Simulation) - 1.96*as.numeric(SE),ymax = as.numeric(Simulation)+1.96*as.numeric(SE)))
          +geom_hline(yintercept=0,linetype="dashed")
          +labs(x="Outcome", y="Proportion")
          +fitrules
          +theme(axis.text=element_text(size=15,color="black"),
                 text= element_text(size=15,color='black'),
                 plot.title = element_text(size=15,color='black',hjust=0.5),legend.justification=c(0,1),legend.position=c(0.7,0.95),
                 legend.title=element_blank(),
                 legend.background=element_rect(color="black"))
          +mytheme
          +coord_cartesian(ylim=c(-0.5,0.4))
    )
    dev.off()
    
    # pdf(paste0(path,'eventstudy',eventtype,'_sim_earnings',marnames[m+1],'.pdf'))
    # print(ggplot(data=eventplot[outcome%in%c('Head Earnings','Spousal Earnings'),])+
    #         geom_point(aes(x=outcome,y=as.numeric(Data),shape="Data"),size=4)
    #       +geom_point(aes(x=outcome,y=as.numeric(Simulation),shape="Simulation"),size=4)
    #       +geom_errorbar(aes(x=outcome, ymin = as.numeric(Simulation) - 1.96*as.numeric(SE),ymax = as.numeric(Simulation)+1.96*as.numeric(SE)))
    #       +geom_hline(yintercept=0,linetype="dashed")
    #       +labs(x="outcome",y="Dollars")
    #       +fitrules
    #       +theme(axis.text=element_text(size=15,color="black"),
    #              text= element_text(size=15,color='black'),
    #              plot.title = element_text(size=15,color='black',hjust=0.5),legend.justification=c(0,1),legend.position=c(0.7,0.2),
    #              legend.title=element_blank(),
    #              legend.background=element_rect(color="black"))
    #       +mytheme
    #       +ylim(-15000,2000)
    # )
    # dev.off()
  }
}

#######EVENT STUDY CODE DONE###################


##############ELASTICITY CODE################
evalelast<-function(path,paramvals, suffix,marriageprob,marriageprob_init,onlysingle=FALSE,onlymarried=FALSE,onlyFT=0,workDI=0){
  ###RESPONSES TO CHANGING BENEFITS:
  ###10%  increase/decrease in benefits ("marginal")
  upper<-1.05
  lower<-0.95
  temp<-paramsetup(paramvals,wagepars,spwagepars,FSgenerosity=1,SSgenerosity=upper)
  params1<-temp$params
  param_input1<-param_input
  rm(temp)
  
  simdata1<-Valsim_solve(as.vector(param_input1),params1,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage), aperm(spWage),
                         shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                         marriageprob_init,numsims,lumpsum=0,print=0,workDI=workDI,onlyFT=onlyFT)
  simdata1<-as.data.table(simdata1)
  
  
  temp<-paramsetup(paramvals,wagepars,spwagepars,FSgenerosity=1,SSgenerosity=lower)
  params0<-temp$params
  param_input0<-param_input
  rm(temp)
  
  simdata0<-Valsim_solve(as.vector(param_input0),params0,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage), aperm(spWage),
                         shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                         marriageprob_init,numsims,lumpsum=0,print=0,workDI=workDI,onlyFT=onlyFT)
  simdata0<-as.data.table(simdata0)
  
  simdata1[,nonWork:=Work==0&Workpart==0]
  simdata0[,nonWork:=Work==0&Workpart==0]
  #Elasticity in DI take-up , over age:
  plotchange<-data.table(age=1:40+22)
  for (a in 1:40) {
    L1 <- sum(simdata1[time+23==a+22,DI==2])
    L0 <- sum(simdata0[time+23==a+22,DI==2])
    plotchange[age==a+22,elasticityDI:=(log(L1)-log(L0))/(upper-lower)]
    
    L1 <- mean(simdata1[time+23==a+22,Work])
    L0 <- mean(simdata0[time+23==a+22,Work])
    plotchange[age==a+22,elasticityWork:=(L1-L0)/(upper-lower)]
    
    L1 <- mean(simdata1[time+23==a+22,C])
    L0 <- mean(simdata0[time+23==a+22,C])
    plotchange[age==a+22,elasticityC:=(L1-L0)/(upper-lower)]
    
    L1 <- sum(simdata1[time+23==a+22,Apply])
    L0 <- sum(simdata0[time+23==a+22,Apply])
    plotchange[age==a+22,elasticityApply:=(log(L1)-log(L0))/(upper-lower)]
    
    L1 <- mean(simdata1[time+23==a+22,nonWork])
    L0 <- mean(simdata0[time+23==a+22,nonWork])
    plotchange[age == a+22, elasticitynonWork := (log(L1)-log(L0))/(upper-lower)]
    #  plotchange[age==a+22,elasticitynonWork:=(log(L1)-log(L0))/(upper-lower)]
  }
  plotchange<-as.data.table(plotchange)
  pdf(paste0(path,"ElasticityDI_overage_",suffix,".pdf"))
  print(ggplot(data=plotchange)+
          geom_line(aes(x=age,y=elasticityDI))+
          labs(y="Elasticity")+
          theme(axis.text=element_text(size=15,color="black"),
                text= element_text(size=15,color='black'),
                plot.title = element_text(size=15,color='black',hjust=0.5),legend.justification=c(0,1),legend.position=c(0.75,0.95),
                legend.background=element_rect(color="black"))
  )
  dev.off()
  
  pdf(paste0(path,"ElasticityApply_overage_",suffix,".pdf"))
  print(ggplot(data=plotchange)+
          geom_line(aes(x=age,y=elasticityApply))+
          labs(y="Elasticity")+
          theme(axis.text=element_text(size=15,color="black"),
                text= element_text(size=15,color='black'),
                plot.title = element_text(size=15,color='black',hjust=0.5),legend.justification=c(0,1),legend.position=c(0.75,0.95),
                legend.background=element_rect(color="black"))
  )
  dev.off()
  
  pdf(paste0(path,"ElasticitynonWork_overage_",suffix,".pdf"))
  print(ggplot(data=plotchange)+
          geom_line(aes(x=age,y=elasticitynonWork))+
          labs(y="Elasticity")+
          theme(axis.text=element_text(size=15,color="black"),
                text= element_text(size=15,color='black'),
                plot.title = element_text(size=15,color='black',hjust=0.5),legend.justification=c(0,1),legend.position=c(0.75,0.95),
                legend.background=element_rect(color="black"))
  )
  dev.off()
  
  simdata1[,married:=as.numeric(single==0)]
  simdata0[,married:=as.numeric(single==0)]
  
  
  L1 <- sum(simdata1[time<=39,DI==2])
  L0 <- sum(simdata0[time<=39,DI==2])
  benelasticity.DI<-(log(L1)-log(L0))/(upper-lower)
  
  L1 <- mean(simdata1[time<=39,Work==0])
  L0 <- mean(simdata0[time<=39,Work==0])
  benelasticity.nonWork<-(log(L1)-log(L0))/(upper-lower)

  L1 <- sum(simdata1[time<=39,Apply])
  L0 <- sum(simdata0[time<=39,Apply])
  benelasticity.Apply<-(log(L1)-log(L0))/(upper-lower)
  
  setorder(simdata1,Health)
  setorder(simdata0,Health)
  L1 <-simdata1[time<=39, sum(DI == 2), by = Health]$V1
  L0 <- simdata0[time<=39,sum(DI == 2), by = Health]$V1
  benelasticity.DI.Health<-(log(L1)-log(L0))/(upper-lower)
  
  L1 <-simdata1[time<=39, sum(Work == 0), by = Health]$V1
  L0 <- simdata0[time<=39,sum(Work == 0), by = Health]$V1
  benelasticity.nonWork.Health<-(log(L1)-log(L0))/(upper-lower)

  L1 <-simdata1[time<=39, sum(Apply), by = Health]$V1
  L0 <- simdata0[time<=39,sum(Apply), by = Health]$V1
  benelasticity.Apply.Health<-(log(L1)-log(L0))/(upper-lower)
  
  setorder(simdata1,married)
  setorder(simdata0,married)
  L1 <- simdata1[time<=39,sum(DI==2),by=married]$V1
  L0 <- simdata0[time<=39,sum(DI==2),by=married]$V1
  benelasticity.DI.Marital<-(log(L1)-log(L0))/(upper-lower)
  
  L1 <- simdata1[time<=39,mean(Work==0), by = married]$V1
  L0 <- simdata0[time<=39,mean(Work==0), by = married]$V1
  benelasticity.nonWork.Marital<-(log(L1)-log(L0))/(upper-lower)
  
  L1 <- simdata1[time<=39,sum(Apply), by = married]$V1
  L0 <- simdata0[time<=39,sum(Apply), by = married]$V1
  benelasticity.Apply.Marital<-(log(L1)-log(L0))/(upper-lower)
  
  
  tbl<-xtable(cbind(benelasticity.DI,benelasticity.nonWork,benelasticity.Apply),type="latex",digits=3)
  colnames(tbl)<-c("DI","Non-Work","Applications")
  print(tbl,file=paste0(path,"benefitelasticity_",suffix,".tex"),tabular.environment='tabular',floating=FALSE,include.colnames=TRUE,include.rownames=TRUE)
  
  
  ###########ELASTICITIES############# - COMPARE TO KEANE (2011)
  #Head Marshallian Elasticity calculations :
  #1/2 st. dev increase 
  upper<-0.5
  lower<--0.5
  temp<-wagesetup_fit(paramvals,upper,0)
  Wage1<-temp$Wage
  spWage1<-temp$spWage
  wagepars1<-temp$wagepars
  spwagepars1<-temp$spwagepars
  rm(temp)
  
  temp<-paramsetup(paramvals,wagepars1,spwagepars1)
  params1<-temp$params
  param_input1<-param_input
  rm(temp)
  
  simdata1<-Valsim_solve(as.vector(param_input1),params1,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage1), aperm(spWage1),
                         shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                         marriageprob_init,numsims,lumpsum=0,print=0,workDI=workDI,onlyFT=onlyFT)
  simdata1<-as.data.table(simdata1)
  #1/2 st. dev decrease
  temp<-wagesetup_fit(paramvals,lower,0)
  Wage0<-temp$Wage
  spWage0<-temp$spWage
  wagepars0<-temp$wagepars
  spwagepars0<-temp$spwagepars
  rm(temp)
  
  temp<-paramsetup(paramvals,wagepars0,spwagepars0)
  params0<-temp$params
  param_input0<-param_input
  rm(temp)
  
  simdata0<-Valsim_solve(as.vector(param_input0),params0,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage0), aperm(spWage0),
                         shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                         marriageprob_init,numsims,lumpsum=0,print=0,workDI=workDI,onlyFT=onlyFT)
  simdata0<-as.data.table(simdata0)

  L1 <- mean(simdata1[time+23<=62 ,Work+Workpart])
  L0 <- mean(simdata0[time+23<=62 ,Work+Workpart])
  plotchange[age==a+23,elasticity:=(log(L1)-log(L0))/(exp(wagepars$wagevar*(upper))-exp(wagepars$wagevar*lower))]
  ownelasticity.work<- (log(L1)-log(L0))/(wagepars$wagevar*(upper)-wagepars$wagevar*lower)
  
  setorder(simdata0,Health)
  setorder(simdata1,Health)
  L1 <- simdata1[time+23<=62,mean(Work+Workpart),by=Health]$V1
  L0 <- simdata0[time+23<=62,mean(Work+Workpart),by=Health]$V1
  ownelasticity.work.Health <- (log(L1)-log(L0))/(wagepars$wagevar*(upper)-wagepars$wagevar*lower)
  
  simdata0[,married:=as.numeric(single==0)]
  simdata1[,married:=as.numeric(single==0)]
  setorder(simdata0,married)
  setorder(simdata1,married)
  L1 <- simdata1[time+23<=62,mean(Work+Workpart),by=married]$V1
  L0 <- simdata0[time+23<=62,mean(Work+Workpart),by=married]$V1
  ownelasticity.work.Marital <- (log(L1)-log(L0))/(wagepars$wagevar*(upper)-wagepars$wagevar*lower)
  
  #Age-specific elasticities:
  plotchange<-foreach (a = 1:40,.combine = 'rbind') %dopar% {
    L1 <- mean(simdata1[time+23==a+22,Work+Workpart])
    L0 <- mean(simdata0[time+23==a+22,Work+Workpart])
    c(age=a+22,elasticity=(log(L1)-log(L0))/(wagepars$wagevar*(upper)-wagepars$wagevar*lower))
  }
  plotchange<-as.data.table(plotchange)
  names(plotchange)<-c("age","elasticity")
  
  pdf(paste0(path,'MarshallianWork_overage_',suffix,'.pdf'))
  print(ggplot(data=plotchange)+
          geom_line(aes(x=age,y=elasticity))+
          theme(axis.text=element_text(size=15,color="black"),
                text= element_text(size=15,color='black'),
                plot.title = element_text(size=15,color='black',hjust=0.5),legend.justification=c(0,1),legend.position=c(0.75,0.95),
                legend.background=element_rect(color="black"))
  )
  dev.off()
  ###########SPOUSES marshallian elasticity:
  if(onlysingle==FALSE){
    upper<-0.5
    lower<--0.5
    temp<-wagesetup_fit(paramvals,0,upper)
    Wage1<-temp$Wage
    spWage1<-temp$Wage
    wagepars1<-temp$wagepars
    spwagepars1<-temp$spwagepars
    rm(temp)
    
    temp<-paramsetup(paramvals,wagepars1,spwagepars1)
    params1<-temp$params
    param_input1<-param_input
    rm(temp)
    
    simdata1<-Valsim_solve(as.vector(param_input1),params1,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage1), aperm(spWage1),
                           shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                           marriageprob_init,numsims,lumpsum=0,print=0,workDI=workDI,onlyFT=onlyFT)
    simdata1<-as.data.table(simdata1)
    #1/2 st. dev decrease
    temp<-wagesetup_fit(paramvals,0,lower)
    Wage0<-temp$Wage
    spWage0<-temp$spWage
    wagepars0<-temp$wagepars
    spwagepars0<-temp$spwagepars
    rm(temp)
    
    temp<-paramsetup(paramvals,wagepars0,spwagepars0)
    params0<-temp$params
    param_input0<-param_input
    rm(temp)
    
    simdata0<-Valsim_solve(as.vector(param_input0),params0,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage0), aperm(spWage0),
                           shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                           marriageprob_init,numsims,lumpsum=0,print=0,workDI=workDI,onlyFT=onlyFT)
    simdata0<-as.data.table(simdata0)
    L1 <- mean(simdata1[time+23<=62 & single == 0,spWork+spWorkpart])
    L0 <- mean(simdata0[time+23<=62 & single == 0,spWork+spWorkpart])
    
    ownelasticity.spwork<- (log(L1)-log(L0))/(spwagepars$wagevar*(upper)-spwagepars$wagevar*lower)
    
    setorder(simdata0,Health)
    setorder(simdata1,Health)
    L1 <- simdata1[time+23<=62 & single == 0,mean(spWork+spWorkpart),by=Health]$V1
    L0 <- simdata0[time+23<=62 & single == 0,mean(spWork+spWorkpart),by=Health]$V1
    ownelasticity.spwork.Health <- (log(L1)-log(L0))/(spwagepars$wagevar*(upper)-spwagepars$wagevar*lower)
    
    simdata0[,married:=as.numeric(single==0)]
    simdata1[,married:=as.numeric(single==0)]
    setorder(simdata0,married)
    setorder(simdata1,married)
    L1 <- simdata1[married == 1 & time+23<=62 & single == 0,mean(spWork+spWorkpart)]
    L0 <- simdata0[married == 1 & time+23<=62 & single == 0,mean(spWork+spWorkpart)]
    ownelasticity.spwork.Marital <- (log(L1)-log(L0))/(spwagepars$wagevar*(upper)-spwagepars$wagevar*lower)
    
    #Age-specific elasticities:
    plotchange<-foreach (a = 1:40,.combine = 'rbind') %dopar% {
      L1 <- mean(simdata1[time+23==a+22 & married == 1,spWork+spWorkpart])
      L0 <- mean(simdata0[time+23==a+22 & married == 1,spWork+spWorkpart])
      c(age=a+22,elasticity=(log(L1)-log(L0))/(spwagepars$wagevar*(upper)-spwagepars$wagevar*lower))
    }
    plotchange<-as.data.table(plotchange)
    names(plotchange)<-c("age","elasticity")
    
    pdf(paste0(path,'MarshallianspWork_overage_',suffix,'.pdf'))
    print(ggplot(data=plotchange)+
            geom_line(aes(x=age,y=elasticity))+
            theme(axis.text=element_text(size=15,color="black"),
                  text= element_text(size=15,color='black'),
                  plot.title = element_text(size=15,color='black',hjust=0.5),legend.justification=c(0,1),legend.position=c(0.75,0.95),
                  legend.background=element_rect(color="black"))
    )
    dev.off()
    #also with Keane~ Average male Marsh. elasticity is 0.06
    #CONSISTENT WITH BLUNDELL!!! Male elasticity of -0.09, female of 0.41 
    
  }
  
  
  
  ###HEAD FRISCH ELASTICITIES - range from 0.08 to 0.54 (Keane)
  #Blundell gets 0.69 for heads, 0.96 for spouses
  upper<-0.5
  lower<--0.5
  agevals<-round(seq(from=0,to=39,length.out=5),0)
  plotchange<-foreach (a = agevals,.combine = 'rbind') %dopar% {
    #increase in wage:
    wageshifter<-rep(1,50)
    spwageshifter<-rep(1,50)
    wageshifter[a+1]<-exp(wagepars$wagevar*(upper))
    temp<-paramsetup(paramvals,wagepars,spwagepars,wageshifter=wageshifter,spwageshifter=spwageshifter)
    params1<-temp$params
    param_input1<-param_input
    rm(temp)
    
    Wage1<-Wage
    Wage1[,a+1,]<-Wage1[,a+1,]*exp(wagepars$wagevar*(upper))
    
    simdata1<-Valsim_solve(as.vector(param_input1),params1,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage1), aperm(spWage),
                           shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                           marriageprob_init,numsims,lumpsum=0,print=0,workDI=workDI,onlyFT=onlyFT)
    simdata1<-as.data.table(simdata1)
    
    
    #decrease in wage:
    wageshifter<-rep(1,50)
    spwageshifter<-rep(1,50)
    wageshifter[a+1]<-exp(wagepars$wagevar*(lower))
    temp<-paramsetup(paramvals,wagepars,spwagepars,wageshifter=wageshifter,spwageshifter=spwageshifter)
    params0<-temp$params
    param_input0<-temp$param_input
    rm(temp)
    
    Wage0<-Wage
    Wage0[,a+1,]<-Wage0[,a+1,]*exp(wagepars$wagevar*(lower))
    
    simdata0<-Valsim_solve(as.vector(param_input0),params0,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage0), aperm(spWage),
                           shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                           marriageprob_init,numsims,lumpsum=0,print=0,workDI=workDI,onlyFT=onlyFT)
    simdata0<-as.data.table(simdata0)
    L1 <- mean(simdata1[time==a,Work+Workpart])
    L0 <- mean(simdata0[time==a,Work+Workpart])
    sumL1 <- sum(simdata1[time==a,Work+Workpart])
    sumL0 <- sum(simdata0[time==a,Work+Workpart])
    denomL1 <- nrow(simdata1[time==a,])
    denomL0 <- nrow(simdata0[time==a,])
    c(age=a+23,elasticity=(log(L1)-log(L0))/(wagepars$wagevar*(upper)-wagepars$wagevar*lower),
      sumL1 = sumL1, sumL0 = sumL0, denomL1 = denomL1, denomL0 = denomL0,
      sumL1.H1= sum(simdata1[time==a & Health == 0,Work+Workpart]), sumL0.H1 = sum(simdata0[time==a& Health == 0,Work+Workpart]),
      denomL1.H1 =nrow(simdata1[time==a & Health == 0,]), denomL0.H1 =nrow(simdata0[time==a& Health == 0,]),
      sumL1.H2= sum(simdata1[time==a & Health == 1,Work+Workpart]), sumL0.H2 = sum(simdata0[time==a& Health == 1,Work+Workpart]),
      denomL1.H2 =nrow(simdata1[time==a & Health == 1,]), denomL0.H2 =nrow(simdata0[time==a& Health == 1,]),
      sumL1.H3= sum(simdata1[time==a& Health == 2,Work+Workpart]), sumL0.H3 = sum(simdata0[time==a& Health == 2,Work+Workpart]),
      denomL1.H3 =nrow(simdata1[time==a& Health == 2,]), denomL0.H3 =nrow(simdata0[time==a& Health == 2,]),
      sumL1.M0= sum(simdata1[time==a& single == 1,Work+Workpart]), sumL0.M0 = sum(simdata0[time==a& single == 1,Work+Workpart]),
      denomL1.M0 =nrow(simdata1[time==a& single == 1,]), denomL0.M0 =nrow(simdata0[time==a& single == 1,]),
      sumL1.M1= sum(simdata1[time==a& single == 0,Work+Workpart]), sumL0.M1 = sum(simdata0[time==a& single == 0,Work+Workpart]),
      denomL1.M1 =nrow(simdata1[time==a& single == 0,]), denomL0.M1 =nrow(simdata0[time==a& single == 0,])
    )
  }
  plotchange<-as.data.table(plotchange)
  names(plotchange)[1:2]<-c("age","elasticity")
  
  pdf(paste0(path,"FrischWork_overage_",suffix,".pdf"))
  print(ggplot(data=plotchange)+
          geom_line(aes(x=age,y=elasticity))+
          theme(axis.text=element_text(size=15,color="black"),
                text= element_text(size=15,color='black'),
                plot.title = element_text(size=15,color='black',hjust=0.5),legend.justification=c(0,1),legend.position=c(0.75,0.95),
                legend.background=element_rect(color="black"))
  )
  dev.off()
  frischelasticity.work<-(log(sum(plotchange$sumL1)/sum(plotchange$denomL1)) - 
                            log(sum(plotchange$sumL0)/sum(plotchange$denomL0)))/(
                              (wagepars$wagevar*(upper)-wagepars$wagevar*lower)
                            )
  frischelasticity.work.Health<-c((log(sum(plotchange$sumL1.H1)/sum(plotchange$denomL1.H1)) - 
                            log(sum(plotchange$sumL0.H1)/sum(plotchange$denomL0.H1))),
                            (log(sum(plotchange$sumL1.H2)/sum(plotchange$denomL1.H2)) - 
                               log(sum(plotchange$sumL0.H2)/sum(plotchange$denomL0.H2))),
                            (log(sum(plotchange$sumL1.H3)/sum(plotchange$denomL1.H3)) - 
                               log(sum(plotchange$sumL0.H3)/sum(plotchange$denomL0.H3)))
  )/(wagepars$wagevar*(upper)-wagepars$wagevar*lower)

  frischelasticity.work.Marital<-c((log(sum(plotchange$sumL1.M0)/sum(plotchange$denomL1.M0)) - 
                                     log(sum(plotchange$sumL0.M0)/sum(plotchange$denomL0.M0))),
                                  (log(sum(plotchange$sumL1.M1)/sum(plotchange$denomL1.M1)) - 
                                     log(sum(plotchange$sumL0.M1)/sum(plotchange$denomL0.M1)))
  )/(wagepars$wagevar*(upper)-wagepars$wagevar*lower)
  
  ####SPOUSAL FRISCH ELASTICITIES:
  if(onlysingle==FALSE){
    upper<-0.5
    lower<--0.5
    plotchange<-foreach (a = agevals,.combine = 'rbind') %dopar% {
      #increase in wage:
      wageshifter<-rep(1,50)
      spwageshifter<-rep(1,50)
      spwageshifter[a+1]<-exp(spwagepars$wagevar*upper)
      temp<-paramsetup(paramvals,wagepars,spwagepars,wageshifter=wageshifter,spwageshifter=spwageshifter)
      params1<-temp$params
      param_input1<-param_input
      rm(temp)
      
      spWage1<-spWage
      spWage1[,a+1,]<-spWage1[,a+1,]*exp(spwagepars$wagevar*(upper))
      
      simdata1<-Valsim_solve(as.vector(param_input1),params1,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage), aperm(spWage1),
                             shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                             marriageprob_init,numsims,lumpsum=0,print=0,workDI=workDI,onlyFT=onlyFT)
      simdata1<-as.data.table(simdata1)
      
      #decrease in wage:
      wageshifter<-rep(1,50)
      spwageshifter<-rep(1,50)
      spwageshifter[a+1]<-exp(spwagepars$wagevar*lower)
      temp<-paramsetup(paramvals,wagepars,spwagepars,wageshifter=wageshifter,spwageshifter=spwageshifter)
      params0<-temp$params
      param_input0<-temp$param_input
      rm(temp)
      
      spWage0<-spWage
      spWage0[,a+1,]<-spWage1[,a+1,]*exp(spwagepars$wagevar*(lower))
      
      simdata0<-Valsim_solve(as.vector(param_input0),params0,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage), aperm(spWage0),
                             shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                             marriageprob_init,numsims,lumpsum=0,print=0,workDI=workDI,onlyFT=onlyFT)
      simdata0<-as.data.table(simdata0)
      

      L1 <- mean(simdata1[time==a & single == 0,spWork+spWorkpart])
      L0 <- mean(simdata0[time==a & single == 0,spWork+spWorkpart])
      sumL1 <- sum(simdata1[time==a & single == 0,spWork+spWorkpart])
      sumL0 <- sum(simdata0[time==a & single == 0,spWork+spWorkpart])
      denomL1 <- nrow(simdata1[time==a & single == 0,])
      denomL0 <- nrow(simdata0[time==a & single == 0,])
      c(age=a+23,elasticity=(log(L1)-log(L0))/(spwagepars$wagevar*(upper)-spwagepars$wagevar*lower),
        sumL1 = sumL1, sumL0 = sumL0, denomL1 = denomL1, denomL0 = denomL0,
        sumL1.H1= sum(simdata1[time==a & Health == 0 & single == 0,spWork+spWorkpart]), sumL0.H1 = sum(simdata0[time==a& Health == 0 & single == 0,spWork+spWorkpart]),
        denomL1.H1 =nrow(simdata1[time==a & Health == 0 & single == 0,]), denomL0.H1 =nrow(simdata0[time==a& Health == 0 & single == 0,]),
        sumL1.H2= sum(simdata1[time==a & Health == 1 & single == 0,spWork+spWorkpart]), sumL0.H2 = sum(simdata0[time==a& Health == 1 & single == 0,spWork+spWorkpart]),
        denomL1.H2 =nrow(simdata1[time==a & Health == 1 & single == 0,]), denomL0.H2 =nrow(simdata0[time==a& Health == 1 & single == 0,]),
        sumL1.H3= sum(simdata1[time==a& Health == 2 & single == 0,spWork+spWorkpart]), sumL0.H3 = sum(simdata0[time==a& Health == 2 & single == 0,spWork+spWorkpart]),
        denomL1.H3 =nrow(simdata1[time==a& Health == 2 & single == 0,]), denomL0.H3 =nrow(simdata0[time==a& Health == 2 & single == 0,])
        )
    }
    plotchange<-as.data.table(plotchange)
    names(plotchange)[1:2]<-c("age","elasticity")
    
    print(names(plotchange))
    frischelasticity.spwork<-mean(plotchange$elasticity)
    
    frischelasticity.spwork<-(log(sum(plotchange$sumL1)/sum(plotchange$denomL1)) - 
                              log(sum(plotchange$sumL0)/sum(plotchange$denomL0)))/(
                                (spwagepars$wagevar*(upper)-spwagepars$wagevar*lower)
                              )
    frischelasticity.spwork.Health<-c((log(sum(plotchange$sumL1.H1)/sum(plotchange$denomL1.H1)) - 
                                       log(sum(plotchange$sumL0.H1)/sum(plotchange$denomL0.H1))),
                                    (log(sum(plotchange$sumL1.H2)/sum(plotchange$denomL1.H2)) - 
                                       log(sum(plotchange$sumL0.H2)/sum(plotchange$denomL0.H2))),
                                    (log(sum(plotchange$sumL1.H3)/sum(plotchange$denomL1.H3)) - 
                                       log(sum(plotchange$sumL0.H3)/sum(plotchange$denomL0.H3)))
    )/(spwagepars$wagevar*(upper)-spwagepars$wagevar*lower)
    
    pdf(paste0(path,"FrischspWork_overage_",suffix,".pdf"))
    print(ggplot(data=plotchange)+
            geom_line(aes(x=age,y=elasticity))+
            theme(axis.text=element_text(size=15,color="black"),
                  text= element_text(size=15,color='black'),
                  plot.title = element_text(size=15,color='black',hjust=0.5),legend.justification=c(0,1),legend.position=c(0.75,0.95),
                  legend.background=element_rect(color="black"))
    )
    dev.off()
  }
  else{
    ownelasticity.spwork<-NA
    frischelasticity.spwork<-NA
  }
  #PRINT NEW ELASTICITIES:
  central_lit<-c(0.7,0.6,0.06,0.4,0.85,0.7)
  range_lit <- c("(0.06,0.93)","(0.2,1.3)","(-0.47,0.51)","(-0.2,1.36)","(0.03,2.75)","(0.03,2.35)")
  print(is.list(benelasticity.nonWork))
  print(is.list(benelasticity.nonWork.Marital))
  print(is.list(benelasticity.nonWork.Health))
  print(is.list(benelasticity.Apply))
  print(is.list(benelasticity.Apply.Marital))
  print(is.list(benelasticity.Apply.Health))
  print(is.list(ownelasticity.work))
  print(is.list(ownelasticity.work.Marital))
  print(is.list(ownelasticity.work.Health))
  print(is.list(ownelasticity.spwork))
  print(is.list(ownelasticity.spwork.Marital))
  print(is.list(ownelasticity.spwork.Health))
  print(is.list(frischelasticity.work))
  print(is.list(frischelasticity.work.Marital))
  print(is.list(frischelasticity.work.Health))
  print(is.list(frischelasticity.spwork))
  print(is.list(frischelasticity.spwork.Health))
  
  tbl<- TR(c("","","by Marital Status","by Health"),cspan=c(1,1,2,3))+
    midrulep(list(c(3,4),c(5,7))) +
#    TR(c("","","Literature","Simulation","Simulation"),cspan=c(1,1,2,2,3)) +
    TR(c("Elasticity",
         "Overall",#"(central)","(range)",
         "Single","Married","Healthy","Mod. Limit","Sev. Limit")) +
    midrulep(list(c(2,2),c(3,3),c(4,4),c(5,5),c(6,6),c(7,7)
                  #,c(8,8),c(9,9)
                  )) +
    TR("Panel A: elasticities with respect to DI benefit generosity", cspan=c(7),surround = "\\textit{%s}") +
    TR("Non-employment")%:%
    TR(c(benelasticity.nonWork),dec=2)%:%#,central_lit[1]), dec=2)%:%
    #TR(range_lit[1])%:%
    TR(c(benelasticity.nonWork.Marital,benelasticity.nonWork.Health), dec=2)+
    TR("Applications")%:%
    TR(c(benelasticity.Apply),dec=2)%:%#,central_lit[2]), dec=2)%:%
    #TR(range_lit[2])%:%
    TR(c(benelasticity.Apply.Marital,benelasticity.Apply.Health), dec=2)+
    vspace(5)+
    TR("Panel B: elasticities with respect to own potential wages", cspan=c(7),surround = "\\textit{%s}") +
    TR("Head, Uncompensated ")%:%
    TR(c(ownelasticity.work),dec=2)%:%#,central_lit[3]), dec=2)%:%
    #TR(range_lit[3])%:%
    TR(c(ownelasticity.work.Marital,ownelasticity.work.Health), dec=2)+
    TR("Spouse, Uncompensated ")%:%
    TR(c(ownelasticity.spwork),dec=2)%:%#,central_lit[4]), dec=2)%:%
    TR("---")%:%
    #TR(c(range_lit[4],"---"))%:%
    TR(c(ownelasticity.spwork.Marital,ownelasticity.spwork.Health), dec=2)+
    TR("Head, Frisch")%:%
    TR(c(frischelasticity.work),dec=2)%:%#,central_lit[5]), dec=2)%:%
    #TR(range_lit[5])%:%
    TR(c(frischelasticity.work.Marital,frischelasticity.work.Health), dec=2)+
    TR("Spouse, Frisch")%:%
    TR(c(frischelasticity.spwork),dec=2)%:%#,central_lit[6]), dec=2)%:%
    TR("---")%:%
    #TR(c(range_lit[6],"---"))%:%
    TR(c(frischelasticity.spwork,frischelasticity.spwork.Health), dec=2)
    
  print("printing elasticity table:")
  
  saveRDS(tbl,file=paste0(path,"elasticityfit_all_",suffix,".RDS"))
  
  # TS(tbl,file="elasticityfit_all",
  #    output_path=path, pretty_rules = T,
  #    header=c('r',rep('c',8)))
  
  ####PRINTING SUMMARY OF ELASTICITIES:
  tbl<-xtable(cbind(c(round(benelasticity.nonWork,3),round(benelasticity.Apply,3),round(ownelasticity.work,3),round(ownelasticity.spwork,3),round(frischelasticity.work,3),round(frischelasticity.spwork,3)),
                    c(0.7,0.6,0.06,0.4,0.85,0.7),
                    c("(0.06,0.93)","(0.2,1.3)","(-0.47,0.51)","(-0.2,1.36)","(0.03,2.75)","(0.03,2.35)")),type="latex",digits=3)
  rownames(tbl)<-c("Nonwork to benefits","Apply to benefits","Head Work, Marsh","Spouse Work, Marsh","Head Work, Frisch", "Spouse Work, Frisch")
  colnames(tbl)<-c("Sim","Lit (central)","Lit (range)")
  align(tbl)<-"l|ccc"
  print(tbl,file=paste0(path,"elasticityfit_",suffix,".tex"),tabular.environment='tabular',floating=FALSE,include.colnames=TRUE,include.rownames=TRUE)
  
}

############ELASTICITY CODE DONE#############


#### WTP CODE #############
####AS AN ANNUAL PRICE:
#V is (type,t,w,spw,a,emp,spemp,dd,hh,sph) in dimension:
construct_wtp<-function(wtp_asset,simdata,policyname){
  wtp_asset[,Work_healthy:=simdata[age<=62 & Health==1 ,mean(Work+Workpart),by=.(initialmar,Type)]$V1]
  wtp_asset[,Work_sick:=simdata[age<=62 & Health==2 ,mean(Work+Workpart),by=.(initialmar,Type)]$V1]
  wtp_asset[,Work_vsick:=simdata[age<=62 & Health==3 ,mean(Work+Workpart),by=.(initialmar,Type)]$V1]
  wtp_asset[,spWork_healthy:=simdata[age<=62 & Health==1 ,mean(spWork+spWorkpart),by=.(initialmar,Type)]$V1]
  wtp_asset[,spWork_sick:=simdata[age<=62 & Health==2 ,mean(spWork+spWorkpart),by=.(initialmar,Type)]$V1]
  wtp_asset[,spWork_vsick:=simdata[age<=62 & Health==3 ,mean(spWork+spWorkpart),by=.(initialmar,Type)]$V1]
  wtp_asset[,DI_healthy:=simdata[age<=62 & Health==1,mean(yearDI),by=.(initialmar,Type)]$V1]
  wtp_asset[,DI_sick:=simdata[age<=62 & Health==2,mean(yearDI),by=.(initialmar,Type)]$V1]
  wtp_asset[,DI_vsick:=simdata[age<=62 & Health==3,mean(yearDI),by=.(initialmar,Type)]$V1]
  wtp_asset[,wtp:=0]
  wtp_asset[,policy:=policyname]
}

cfacts<-function(maindata,cdata,params){
  meanV0<-mean(maindata[time==0,V])
  meanV1<-mean(cdata[time==0,V])
  newcons <- cdata[,sum(C/params$R^time)]
  wtp <- 1-(meanV0/meanV1)^(1/(1-params$gamma))
  wtpcash <- wtp*newcons/nrow(maindata)
  
  cbudget1 <- maindata[,sum(NetTax/(params$R^time))] - maindata[,sum(Transfers/(params$R^time))] - maindata[,sum(reassessed/(params$R^time))]*params$cost_reassess
  cbudget0 <- cdata[,sum(NetTax/(params$R^time))] - cdata[,sum(Transfers/(params$R^time))] - cdata[,sum(reassessed/(params$R^time))]*params$cost_reassess
  constax <- (cbudget0 - cbudget1)/newcons
  constaxcash <- (cbudget0 - cbudget1)/nrow(maindata)
  
  gain <- wtpcash - constaxcash
  mvpf <- wtp/constax
  
  maindata<-maindata[order(single,Type),]
  cdata<-cdata[order(single,Type),]
  
  work <- (cdata[age <= 62,mean(Work)] - maindata[age <= 62,mean(Work)])*100
  names(work)<-"work"
  DI <- (cdata[age <= 62,mean(yearDI)] - maindata[age <= 62,mean(yearDI)])*100
  names(DI)<-"DI"
  work_bygroup <- (cdata[age <= 62,mean(Work),by=.(Type,single)]$V1 - maindata[age <= 62,mean(Work),by=.(Type,single)]$V1)*100
  names(work_bygroup)<-c("work.m.1","work.m.2","work.m.3","work.s.1","work.s.2","work.s.3")
  DI_bygroup <- (cdata[age <= 62,mean(yearDI),by=.(Type,single)]$V1 - maindata[age <= 62,mean(yearDI),by=.(Type,single)]$V1)*100
  names(DI_bygroup)<-c("DI.m.1","DI.m.2","DI.m.3","DI.s.1","DI.s.2","DI.s.3")
  values <- c(wtp,wtpcash,constax,constaxcash,gain,mvpf,work,work_bygroup,DI,DI_bygroup)
  names(values)<-c("wtp","wtpcash","constax","constaxcash","gain","mvpf","work","work_bygroup","DI","DI_bygroup")
  return(values)
}

wtpfun<-function(wtp_wage,
                 param_input1,params1,
                 workDI1,earlyDI1,jointtax1, nosave1, DI_meanstest1,
                 param_input0,params0,
                 workDI0,earlyDI0,jointtax0, nosave0, DI_meanstest0,
                 marriageprob, healthprob, 
                 Wage,spWage, shocks.wage, shocks.spwage, marriageprob_init,
                 foodstamps, numkids, oecd,
                 policyname,lumpname,onlyFT,onlysingle,onlymarried,noshaw,
                 noshaw_ib=noshaw_ib,
                 noshaw_iball=noshaw_iball,                 
                 noSSDI1 = 0,
                 noSSDI0 = 0,
                 basedata="main",
                 filename){
  simdata1<-Valsim_solve(as.vector(param_input1),params1,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage), aperm(spWage),
                         shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                         marriageprob_init,numsims,
                         lumpsum=0,
                         print=0,onlyFT=onlyFT,onlysingle=onlysingle,onlymarried=onlymarried,
                         workDI=workDI1,earlyDI=earlyDI1,jointtax= jointtax1, nosave = nosave1, noSSDI = noSSDI1, DI_meanstest = DI_meanstest1)
  simdata1<-cleansim(simdata1,select=select,selectC=selectC)
  if(earlyDI1==1) simdata1[,Apply:=c(0,Apply[-.N]),by=i] #Apply in this case really is tied to next period
  simdata1[,everApply:=max(Apply),by=i]
  simdata1[,MoralHazard:=Wage*exp(wagepars$wagereg[[Type]]$health[[Health]])*params$hours*moralhazard(Ceq,Work,spWork,single,Health,spHealth,Wage*params$hours,spWage*params$hours,time,ageold,yearDI,Apply,numkids,Type,param_input),by=row]
  simdata1[,firstApply:=time==min(time*Apply+99999*(Apply==0)),by=i]
  simdata1[,married:=1-single]
  simdata1[,initialmar:=max((age==min(age))*married),by=i]
  simdata1<-simdata1[order(initialmar,Type),]
  
  
  event1<-const_moments(output=simdata1,shocks.wagenoise=shocks.wagenoise,shocks.spwagenoise=shocks.spwagenoise,onlysingle=0,onlymarried=0,onlyFT=1,onlyevent=TRUE)
  
  
  if(basedata=="meanstest" | basedata == "meanstestnoSSDI"){
    simdata0<-Valsim_solve(as.vector(param_input0),params0,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage), aperm(spWage),
                           shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                           marriageprob_init,numsims,
                           lumpsum=0,
                           print=0,onlyFT=onlyFT,onlysingle=onlysingle,onlymarried=onlymarried,
                           workDI=workDI0,earlyDI=earlyDI0,jointtax= jointtax0, nosave = nosave0, noSSDI = noSSDI0, DI_meanstest = DI_meanstest0)
    simdata0<-cleansim(simdata0,select=select,selectC=selectC)
    if(earlyDI0==1) simdata0[,Apply:=c(0,Apply[-.N]),by=i] #Apply in this case really is tied to next period
    simdata0[,everApply:=max(Apply),by=i]
    simdata0[,MoralHazard:=Wage*exp(wagepars$wagereg[[Type]]$health[[Health]])*params$hours*moralhazard(Ceq,Work,spWork,single,Health,spHealth,Wage*params$hours,spWage*params$hours,time,ageold,yearDI,Apply,numkids,Type,param_input),by=row]
    simdata0[,firstApply:=time==min(time*Apply+99999*(Apply==0)),by=i]
    
    wtp_wage[,realflow:=flow] 
    simdata0[,married:=1-single]
    simdata0[,initialmar:=max((age==min(age))*married),by=i]
    simdata0<-simdata0[order(initialmar,Type),]
    
    event0<-const_moments(output=simdata0,shocks.wagenoise=shocks.wagenoise,shocks.spwagenoise=shocks.spwagenoise,onlysingle=0,onlymarried=0,onlyFT=1,onlyevent=TRUE)
    
    simdata0[simdata1,Apply1:=i.Apply,on="row"]
    
    wtp_wage[simdata0,Apply0:=i.Apply,on="row"]
    wtp_wage[simdata0,flow:=i.flow,on="row"]
    meanV<-mean(simdata0[time==0,V])
    meanflow<-mean(abs(simdata0[age <= 62,flow]))
    emp0 <- simdata0[age <= 62,mean(Work)]
    everapply0 <- simdata0[age <= 62  ,mean(everApply)]
    moralhazard0 <- simdata0[age <= 62 & (yearDI==1 | Apply==1),sum(MoralHazard)]
    selection0 <- simdata0[age <= 62 & Apply==1,mean(VonDI-VnoDI)]
    apply0 <- simdata0[age <= 62  & yearDI==0 & DI == 1,mean(Apply)]
    rolls0 <- simdata0[age <= 62,mean(yearDI)]
    cbudget <- simdata0[,sum(NetTax/(params$R^time))] - simdata0[,sum(Transfers/(params$R^time))] - simdata0[,sum(reassessed/(params$R^time))]*params$cost_reassess
    cbudget_nore <- simdata0[,sum(NetTax/(params$R^time))] - simdata0[,sum(Transfers/(params$R^time))] 
    
    selection1 <- simdata0[age <= 62 & Apply1==1,mean(VonDI-VnoDI)] 
    
  }
  else{
    wtp_wage[,Apply0:=Apply,]
    wtp_wage[,MoralHazard:=Wage*exp(wagepars$wagereg[[Type]]$health[[Health]])*params$hours*moralhazard(Ceq,Work,spWork,single,Health,spHealth,Wage*params$hours,spWage*params$hours,time,ageold,yearDI,Apply,numkids,Type,param_input),by=row]
    wtp_wage[simdata1,Apply1:=i.Apply,on="row"]
    
    meanV<-mean(wtp_wage[time==0,V])
    meanflow<-mean(abs(wtp_wage[age <= 62,flow]))
    emp0 <- wtp_wage[age <= 62,mean(Work)]
    everapply0 <- wtp_wage[age <= 62  ,mean(everApply)]
    moralhazard0 <- wtp_wage[age <= 62 & (yearDI==1 | Apply==1),sum(MoralHazard)]
    selection0 <- wtp_wage[age <= 62 & Apply0==1,mean(VonDI-VnoDI)]
    apply0 <- wtp_wage[age <= 62  & yearDI==0 & DI == 1,mean(Apply)]
    rolls0 <- wtp_wage[age <= 62,mean(yearDI)]
    cbudget <- wtp_wage[,sum(NetTax/(params$R^time))] - wtp_wage[,sum(Transfers/(params$R^time))] - wtp_wage[,sum(reassessed/(params$R^time))]*params$cost_reassess
    cbudget_nore <- wtp_wage[,sum(NetTax/(params$R^time))] - wtp_wage[,sum(Transfers/(params$R^time))] 

    event0<-const_moments(output=wtp_wage,shocks.wagenoise=shocks.wagenoise,shocks.spwagenoise=shocks.spwagenoise,onlysingle=0,onlymarried=0,onlyFT=1,onlyevent=TRUE)
    
    selection1 <- wtp_wage[age <= 62 & Apply1==1,mean(VonDI-VnoDI)] 
    
  }
  meanV1<-mean(simdata1[time==0,V])
  emp1 <- simdata1[age <= 62,mean(Work)]
  everapply1 <- simdata1[age <= 62  ,mean(everApply)]
  moralhazard1 <- simdata1[age <= 62 & (yearDI==1 | Apply==1),sum(MoralHazard)]
  apply1 <- simdata1[age <= 62 & yearDI==0 & DI == 1,mean(Apply)]
  rolls1 <- simdata1[age <= 62,mean(yearDI)]
  cbudget1 <- simdata1[,sum(NetTax/(params$R^time))] - simdata1[,sum(Transfers/(params$R^time))] - simdata1[,sum(reassessed/(params$R^time))]*params$cost_reassess
  cbudget1_nore <- simdata1[,sum(NetTax/(params$R^time))] - simdata1[,sum(Transfers/(params$R^time))] 
  newcons <- simdata1[,sum(C/params$R^time)]
  print(paste0("Evaluating wage:",policyname))
  wtp_wage[simdata1,eval(lumpname):=1-(V/i.V)^(1/(1-params$gamma)),on="row"]
  print(paste0("Finding ex-ante WTP:",policyname))
  wtp_wage[,eval(paste0("emp_",lumpname)):=emp1 - emp0]
  wtp_wage[,eval(paste0("everapply_",lumpname)):=everapply1 - everapply0]
  wtp_wage[,eval(paste0("selection_",lumpname)):=(selection1 - selection0)/selection0]
  wtp_wage[,eval(paste0("moralhazard_",lumpname)):=(moralhazard1 - moralhazard0)/.N]
  wtp_wage[,eval(paste0("apply_",lumpname)):=apply1 - apply0]
  wtp_wage[,eval(paste0("rolls_",lumpname)):=rolls1 - rolls0]
  wtp_wage[,eval(paste0("exante_",lumpname)):=1-(meanV/meanV1)^(1/(1-params$gamma))]
  wtp_wage[,eval(paste0("exantecash_",lumpname)):=(1-(meanV/meanV1)^(1/(1-params$gamma)))*newcons/nrow(wtp_wage)]
  wtp_wage[,eval(paste0("constaxcash_",lumpname)):=(cbudget - cbudget1)/nrow(wtp_wage)]
  wtp_wage[,eval(paste0("constax_",lumpname)):=(cbudget - cbudget1)/newcons]
  wtp_wage[,eval(paste0("constax_nore_",lumpname)):=(cbudget_nore - cbudget1_nore)/newcons]

  
  
   wtp_wage[simdata1,eval(paste0("MU_",lumpname)) := i.C^(-params$gamma)*((i.Ceq/i.C)^(1-params$gamma)),on="row"] #Note MU depends on EQUIVALIZED consumption.

  
   event<-merge(event0,event1,by=c("event_time","single"))
   setnames(event,c("V1.x","V1.y"),c("DI_baseline","DI_counterfactual"))
   write.csv(event,paste0("./figures/wtp_decompose/eventDI_",filename,"_",lumpname,".csv"))
  
  for(typ in 1:3){
    meanV1<-mean(simdata1[time==0&Type==typ,V])
    emp1 <- simdata1[age <= 62 & Type==typ,mean(Work)]
    everapply1 <- simdata1[age <= 62 & Type==typ  ,mean(everApply)]
    moralhazard1 <- simdata1[age <= 62 & Type==typ & (yearDI==1 | Apply==1),sum(MoralHazard)]
    selection1 <- wtp_wage[age <= 62 & Type==typ & Apply1==1,mean(VonDI-VnoDI)]
    apply1 <- simdata1[age <= 62  & yearDI==0 & DI == 1 & Type==typ,mean(Apply)]
    rolls1 <- simdata1[age <= 62 & Type==typ,mean(yearDI)]
    rollsH11 <- simdata1[age <= 62 & Type==typ&Health==1,mean(yearDI)]
    rollsH21 <- simdata1[age <= 62 & Type==typ&Health==2,mean(yearDI)]
    rollsH31 <- simdata1[age <= 62 & Type==typ&Health==3,mean(yearDI)]
    everapplyH11 <- simdata1[age <= 62 & Type==typ&Health==1  ,mean(everApply)]
    everapplyH21 <- simdata1[age <= 62 & Type==typ&Health==2  ,mean(everApply)]
    everapplyH31 <- simdata1[age <= 62 & Type==typ&Health==3  ,mean(everApply)]
    everapplyH11lowA <- simdata1[age <= 62 & Type==typ&Health==1 & Asset<=5000 ,mean(everApply)]
    everapplyH21lowA <- simdata1[age <= 62 & Type==typ&Health==2 & Asset<=5000 ,mean(everApply)]
    everapplyH31lowA <- simdata1[age <= 62 & Type==typ&Health==3 & Asset<=5000 ,mean(everApply)]
    

    if(basedata%in%c("meanstest","meanstestnoSSDI")){
      cbudget <- simdata0[Type==typ,sum(NetTax/(params$R^time))] - simdata0[Type==typ,sum(Transfers/(params$R^time))]
      meanV<-mean(simdata0[time==0&Type==typ,V])
      emp0 <- simdata0[age <= 62 & Type==typ,mean(Work)]
      everapply0 <- simdata0[age <= 62 & Type==typ  ,mean(everApply)]
      moralhazard0 <- simdata0[age <= 62 & Type==typ & (yearDI==1 | Apply==1),sum(MoralHazard)]
      selection0 <- wtp_wage[age <= 62 & Type==typ & Apply0==1,mean(VonDI-VnoDI)]
      apply0 <- simdata0[age <= 62  & yearDI==0 & DI == 1 & Type==typ,mean(Apply)]
      rolls0 <- simdata0[age <= 62 & Type==typ,mean(yearDI)]
      rollsH10 <- simdata0[age <= 62 & Type==typ&Health==1,mean(yearDI)]
      rollsH20 <- simdata0[age <= 62 & Type==typ&Health==2,mean(yearDI)]
      rollsH30 <- simdata0[age <= 62 & Type==typ&Health==3,mean(yearDI)]
      everapplyH10 <- simdata0[age <= 62 & Type==typ&Health==1  ,mean(everApply)]
      everapplyH20 <- simdata0[age <= 62 & Type==typ&Health==2  ,mean(everApply)]
      everapplyH30 <- simdata0[age <= 62 & Type==typ&Health==3  ,mean(everApply)]
      everapplyH10lowA <- simdata0[age <= 62 & Type==typ&Health==1 & Asset<=5000 ,mean(everApply)]
      everapplyH20lowA <- simdata0[age <= 62 & Type==typ&Health==2 & Asset<=5000 ,mean(everApply)]
      everapplyH30lowA <- simdata0[age <= 62 & Type==typ&Health==3 & Asset<=5000 ,mean(everApply)]
    }
    else{
    cbudget <- wtp_wage[Type==typ,sum(NetTax/(params$R^time))] - wtp_wage[Type==typ,sum(Transfers/(params$R^time))]
    meanV<-mean(wtp_wage[time==0&Type==typ,V])
    emp0 <- wtp_wage[age <= 62 & Type==typ,mean(Work)]
    everapply0 <- wtp_wage[age <= 62 & Type==typ  ,mean(everApply)]
    moralhazard0 <- wtp_wage[age <= 62 & Type==typ & (yearDI==1 | Apply==1),sum(MoralHazard)]
    selection0 <- wtp_wage[age <= 62 & Type==typ & Apply0==1,mean(VonDI-VnoDI)]
    apply0 <- wtp_wage[age <= 62  & yearDI==0 & DI == 1 & Type==typ,mean(Apply)]
    rolls0 <- wtp_wage[age <= 62 & Type==typ,mean(yearDI)]
    rollsH10 <- wtp_wage[age <= 62 & Type==typ&Health==1,mean(yearDI)]
    rollsH20 <- wtp_wage[age <= 62 & Type==typ&Health==2,mean(yearDI)]
    rollsH30 <- wtp_wage[age <= 62 & Type==typ&Health==3,mean(yearDI)]
    everapplyH10 <- wtp_wage[age <= 62 & Type==typ&Health==1  ,mean(everApply)]
    everapplyH20 <- wtp_wage[age <= 62 & Type==typ&Health==2  ,mean(everApply)]
    everapplyH30 <- wtp_wage[age <= 62 & Type==typ&Health==3  ,mean(everApply)]
    everapplyH10lowA <- wtp_wage[age <= 62 & Type==typ&Health==1 & Asset<=5000 ,mean(everApply)]
    everapplyH20lowA <- wtp_wage[age <= 62 & Type==typ&Health==2 & Asset<=5000 ,mean(everApply)]
    everapplyH30lowA <- wtp_wage[age <= 62 & Type==typ&Health==3 & Asset<=5000 ,mean(everApply)]
    }
    cbudget1 <- simdata1[Type==typ,sum(NetTax/(params$R^time))] - simdata1[Type==typ,sum(Transfers/(params$R^time))]
    newcons <- simdata1[Type==typ,sum(C/params$R^time)]
    wtp_wage[Type==typ,eval(paste0("exanteType_",lumpname)):=1-(meanV/meanV1)^(1/(1-params$gamma))]
    wtp_wage[Type==typ,eval(paste0("exantecashType_",lumpname)):=(1-(meanV/meanV1)^(1/(1-params$gamma)))*newcons/nrow(wtp_wage[Type==typ,])]
    wtp_wage[Type==typ,eval(paste0("constaxcashType_",lumpname)):=(cbudget - cbudget1)/nrow(wtp_wage[Type==typ,])]
    wtp_wage[Type==typ,eval(paste0("empType_",lumpname)):=emp1 - emp0]
    wtp_wage[Type==typ,eval(paste0("everapplyType_",lumpname)):=everapply1 - everapply0]
    wtp_wage[Type==typ,eval(paste0("applyType_",lumpname)):=apply1 - apply0]
    wtp_wage[Type==typ,eval(paste0("moralhazardType_",lumpname)):=(moralhazard1 - moralhazard0)/.N]
    wtp_wage[Type==typ,eval(paste0("selectionType_",lumpname)):=(selection1 - selection0)/selection0]
    wtp_wage[Type==typ,eval(paste0("everapplyTypeH1lowA_",lumpname)):=everapplyH11lowA - everapplyH10lowA]
    wtp_wage[Type==typ,eval(paste0("everapplyTypeH2lowA_",lumpname)):=everapplyH21lowA - everapplyH20lowA]
    wtp_wage[Type==typ,eval(paste0("everapplyTypeH3lowA_",lumpname)):=everapplyH31lowA - everapplyH30lowA]
  }
  # 
  for(sing in 0:1){
    if(basedata%in%c("meanstest","meanstestnoSSDI")){
      meanV<-mean(simdata0[time==0&single==sing,V])
      emp0 <- simdata0[age <= 62 & single==sing,mean(Work)]
      apply0 <- simdata0[age <= 62 & single==sing,mean(Apply)]
      rolls0 <- simdata0[age <= 62 & single==sing,mean(yearDI)]
      rolls0H1 <- simdata0[age <= 62 & single==sing&Health==1,mean(yearDI)]
      rolls0H2 <- simdata0[age <= 62 & single==sing&Health==2,mean(yearDI)]
      rolls0H3 <- simdata0[age <= 62 & single==sing&Health==3,mean(yearDI)]
    }
    else{
    meanV<-mean(wtp_wage[time==0&single==sing,V])
    emp0 <- wtp_wage[age <= 62 & single==sing,mean(Work)]
    apply0 <- wtp_wage[age <= 62 & single==sing,mean(Apply)]
    rolls0 <- wtp_wage[age <= 62 & single==sing,mean(yearDI)]
    rolls0H1 <- wtp_wage[age <= 62 & single==sing&Health==1,mean(yearDI)]
    rolls0H2 <- wtp_wage[age <= 62 & single==sing&Health==2,mean(yearDI)]
    rolls0H3 <- wtp_wage[age <= 62 & single==sing&Health==3,mean(yearDI)]
    
    }
    meanV1<-mean(simdata1[time==0&single==sing,V])
    emp1 <- simdata1[age <= 62 & single==sing,mean(Work)]
    apply1 <- simdata1[age <= 62 & single==sing,mean(Apply)]
    rolls1 <- simdata1[age <= 62 & single==sing,mean(yearDI)]
    rolls1H1 <- simdata1[age <= 62 & single==sing&Health==1,mean(yearDI)]
    rolls1H2 <- simdata1[age <= 62 & single==sing&Health==2,mean(yearDI)]
    rolls1H3 <- simdata1[age <= 62 & single==sing&Health==3,mean(yearDI)]
    wtp_wage[single==sing,eval(paste0("rollsMarH1_",lumpname)):=rolls1H1 - rolls0H1]
    wtp_wage[single==sing,eval(paste0("rollsMarH2_",lumpname)):=rolls1H2 - rolls0H2]
    wtp_wage[single==sing,eval(paste0("rollsMarH3_",lumpname)):=rolls1H3 - rolls0H3]
    if(basedata%in%c("meanstest","meanstestnoSSDI")){
      cbudget <- simdata0[single==sing,sum(NetTax/(params$R^time))] - simdata0[single==sing,sum(Transfers/(params$R^time))]
    }
    else{
      cbudget <- wtp_wage[single==sing,sum(NetTax/(params$R^time))] - wtp_wage[single==sing,sum(Transfers/(params$R^time))]
    }
    cbudget1 <- simdata1[single==sing,sum(NetTax/(params$R^time))] - simdata1[single==sing,sum(Transfers/(params$R^time))]
    newcons <- simdata1[single==sing,sum(C/params$R^time)]

  }
  
  for(typ in 1:3){
    for(sing in 0:1){
      if(basedata%in%c("meanstest","meanstestnoSSDI")){
        meanV<-mean(simdata0[time==0&single==sing&Type==typ,V])
        emp0 <- simdata0[age <= 62 & single==sing&Type==typ,mean(Work)]
        everapply0 <- simdata0[age <= 62 & single==sing & Type==typ ,mean(everApply)]
        moralhazard0 <- simdata0[age <= 62 & Type==typ& single==sing & (yearDI==1 | Apply==1),sum(MoralHazard)]
        selection0 <- wtp_wage[age <= 62 & Type==typ& single==sing & Apply0==1,mean(VonDI-VnoDI)]
        apply0 <- simdata0[age <= 62  & yearDI==0 & DI == 1 & single==sing&Type==typ,mean(Apply)]
        rolls0 <- simdata0[age <= 62 & single==sing&Type==typ,mean(yearDI)]
        rollsH10 <- simdata0[age <= 62 & single==sing&Type==typ&Health==1,mean(yearDI)]
        rollsH20 <- simdata0[age <= 62 & single==sing&Type==typ&Health==2,mean(yearDI)]
        rollsH30 <- simdata0[age <= 62 & single==sing&Type==typ&Health==3,mean(yearDI)]
        everapplyH10 <- simdata0[age <= 62 & single==sing&Type==typ&Health==1,mean(everApply)]
        everapplyH20 <- simdata0[age <= 62 & single==sing&Type==typ&Health==2,mean(everApply)]
        everapplyH30 <- simdata0[age <= 62 & single==sing&Type==typ&Health==3,mean(everApply)]
        everapplyH10lowA <- simdata0[age <= 62 & single==sing&Type==typ&Health==1 & Asset <= 5000,mean(everApply)]
        everapplyH20lowA <- simdata0[age <= 62 & single==sing&Type==typ&Health==2 & Asset <= 5000,mean(everApply)]
        everapplyH30lowA <- simdata0[age <= 62 & single==sing&Type==typ&Health==3 & Asset <= 5000,mean(everApply)]
      }
      else{
      meanV<-mean(wtp_wage[time==0&single==sing&Type==typ,V])
      emp0 <- wtp_wage[age <= 62 & single==sing&Type==typ,mean(Work)]
      everapply0 <- wtp_wage[age <= 62 & single==sing & Type==typ ,mean(everApply)]
      moralhazard0 <- wtp_wage[age <= 62 & Type==typ& single==sing & (yearDI==1 | Apply==1),sum(MoralHazard)]
      selection0 <- wtp_wage[age <= 62 & Type==typ& single==sing & Apply0==1,mean(VonDI-VnoDI)]
      apply0 <- wtp_wage[age <= 62  & yearDI==0 & DI == 1 & single==sing&Type==typ,mean(Apply)]
      rolls0 <- wtp_wage[age <= 62 & single==sing&Type==typ,mean(yearDI)]
      rollsH10 <- wtp_wage[age <= 62 & single==sing&Type==typ&Health==1,mean(yearDI)]
      rollsH20 <- wtp_wage[age <= 62 & single==sing&Type==typ&Health==2,mean(yearDI)]
      rollsH30 <- wtp_wage[age <= 62 & single==sing&Type==typ&Health==3,mean(yearDI)]
      everapplyH10 <- wtp_wage[age <= 62 & single==sing&Type==typ&Health==1,mean(everApply)]
      everapplyH20 <- wtp_wage[age <= 62 & single==sing&Type==typ&Health==2,mean(everApply)]
      everapplyH30 <- wtp_wage[age <= 62 & single==sing&Type==typ&Health==3,mean(everApply)]
      everapplyH10lowA <- wtp_wage[age <= 62 & single==sing&Type==typ&Health==1 & Asset <= 5000,mean(everApply)]
      everapplyH20lowA <- wtp_wage[age <= 62 & single==sing&Type==typ&Health==2 & Asset <= 5000,mean(everApply)]
      everapplyH30lowA <- wtp_wage[age <= 62 & single==sing&Type==typ&Health==3 & Asset <= 5000,mean(everApply)]
      }
      meanV1<-mean(simdata1[time==0&single==sing&Type==typ,V])
      emp1 <- simdata1[age <= 62 & single==sing&Type==typ,mean(Work)]
      everapply1 <- simdata1[age <= 62 & single==sing & Type==typ ,mean(everApply)]
      moralhazard1 <- simdata1[age <= 62 & Type==typ& single==sing & (yearDI==1 | Apply==1),sum(MoralHazard)]
      selection1 <- wtp_wage[age <= 62 & Type==typ& single==sing & Apply1==1,mean(VonDI-VnoDI)]
      apply1 <- simdata1[age <= 62  & yearDI==0 & DI == 1 & single==sing&Type==typ,mean(Apply)]
      rolls1 <- simdata1[age <= 62 & single==sing&Type==typ,mean(yearDI)]
      rollsH11 <- simdata1[age <= 62 & single==sing&Type==typ&Health==1,mean(yearDI)]
      rollsH21 <- simdata1[age <= 62 & single==sing&Type==typ&Health==2,mean(yearDI)]
      rollsH31 <- simdata1[age <= 62 & single==sing&Type==typ&Health==3,mean(yearDI)]
      everapplyH11 <- simdata1[age <= 62 & single==sing&Type==typ&Health==1,mean(everApply)]
      everapplyH21 <- simdata1[age <= 62 & single==sing&Type==typ&Health==2,mean(everApply)]
      everapplyH31 <- simdata1[age <= 62 & single==sing&Type==typ&Health==3,mean(everApply)]
      everapplyH11lowA <- simdata1[age <= 62 & single==sing&Type==typ&Health==1 & Asset <= 5000,mean(everApply)]
      everapplyH21lowA <- simdata1[age <= 62 & single==sing&Type==typ&Health==2 & Asset <= 5000,mean(everApply)]
      everapplyH31lowA <- simdata1[age <= 62 & single==sing&Type==typ&Health==3 & Asset <= 5000,mean(everApply)]
      wtp_wage[single==sing&Type==typ,eval(paste0("exanteMarType_",lumpname)):=1-(meanV/meanV1)^(1/(1-params$gamma))]
      wtp_wage[single==sing&Type==typ,eval(paste0("empMarType_",lumpname)):=emp1 - emp0]
      wtp_wage[single==sing&Type==typ,eval(paste0("everapplyMarType_",lumpname)):=everapply1 - everapply0]
      wtp_wage[single==sing&Type==typ,eval(paste0("moralhazardMarType_",lumpname)):=(moralhazard1 - moralhazard0)/.N]
      wtp_wage[single==sing&Type==typ,eval(paste0("selectionMarType_",lumpname)):=(selection1 - selection0)/selection0]
      wtp_wage[single==sing&Type==typ,eval(paste0("applyMarType_",lumpname)):=apply1 - apply0]
      wtp_wage[single==sing&Type==typ,eval(paste0("everapplyMarTypeH1_",lumpname)):=everapplyH11 - everapplyH10]
      wtp_wage[single==sing&Type==typ,eval(paste0("everapplyMarTypeH2_",lumpname)):=everapplyH21 - everapplyH20]
      wtp_wage[single==sing&Type==typ,eval(paste0("everapplyMarTypeH3_",lumpname)):=everapplyH31 - everapplyH30]
      wtp_wage[single==sing&Type==typ & Asset <= 5000,eval(paste0("everapplyMarTypeH1lowA_",lumpname)):=everapplyH11lowA - everapplyH10lowA]
      wtp_wage[single==sing&Type==typ & Asset <= 5000,eval(paste0("everapplyMarTypeH2lowA_",lumpname)):=everapplyH21lowA - everapplyH20lowA]
      wtp_wage[single==sing&Type==typ & Asset <= 5000,eval(paste0("everapplyMarTypeH3lowA_",lumpname)):=everapplyH31lowA - everapplyH30lowA]
      newcons <- simdata1[Type==typ&single==sing,sum(C/params$R^time)]

    }
  }
  
  if(basedata%in%c("meanstest","meanstestnoSSDI")){
    meanV<-mean(simdata0[time==0&everApply==1,V])    
  }
  else{
  meanV<-mean(wtp_wage[time==0&everApply==1,V])
  }
  meanV1<-mean(simdata1[time==0&everApply==1,V])
  wtp_wage[,eval(paste0("exanteApply_",lumpname)):=1-(meanV/meanV1)^(1/(1-params$gamma))]
  
  
  if(basedata%in%c("meanstest","meanstestnoSSDI")){
    meanV<-mean(simdata0[firstApply==1,V])
  }
  else{
  meanV<-mean(wtp_wage[firstApply==1,V])
  }
  meanV1<-mean(simdata1[firstApply==1,V])
  wtp_wage[,eval(paste0("Apply_",lumpname)):=1-(meanV/meanV1)^(1/(1-params$gamma))]
  
  
  if(noshaw!=TRUE){
    if(basedata%in%c("meanstest","meanstestnoSSDI")){
      lumpvals<- find_shawdecomp(simdata0,simdata1, params0,params1,noshaw_ib,noshaw_iball)
    }
    else{
    lumpvals<- find_shawdecomp(wtp_wage,simdata1, params0,params1,noshaw_ib,noshaw_iball)
    }
    
    saveRDS(lumpvals,"lumpvals.RDS")
    
    shawnum<-1
    if(noshaw_ib==TRUE){
      shawnames<-c("GV","RB","RW")
      decomps<- c("giveaway", "redist.between", "redist.within")
    }
    else if(noshaw_iball == TRUE){
      shawnames<-c("GV","RB","RW","IB","IM")
      decomps<- c("giveaway", "redist.between", "redist.within", "insur.between","insur.betweenmar")
    }
    else{
      shawnames<-c("GV","RB","RW","IB","IM","IA")
      decomps<- c("giveaway", "redist.between", "redist.within", "insur.between","insur.betweenmar","insur.betweenall")
    }
    for(decomp in decomps){
      print(paste0("Evaluating wage:", shawnames[shawnum],": ",policyname))
      print(paste("length of shawvec:",length(lumpvals[[decomp]])))
      print(paste("null values:",sum(is.null(lumpvals[[decomp]]))))
      print(paste("NA values:",sum(is.na(lumpvals[[decomp]]))))
      print(summary(lumpvals[[decomp]]))
      simdata1<-Valsim_solve(as.vector(param_input0),params0,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage), aperm(spWage),
                             shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                             marriageprob_init,numsims,
                             lumpsum=lumpvals[[decomp]],
                             print=0,onlyFT=onlyFT,onlysingle=onlysingle,onlymarried=onlymarried,
                             workDI=workDI0,earlyDI=earlyDI0,jointtax= jointtax0, nosave = nosave0, noSSDI = noSSDI0, DI_meanstest = DI_meanstest0)
      simdata1<-cleansim(simdata1,select,selectC)
      wtp_wage[simdata1,eval(paste0(shawnames[shawnum],lumpname)):=1-(V/i.V)^(1/(1-params$gamma)),on="row"]
      meanV<-mean(wtp_wage[time==0,V])
      meanV1<-mean(simdata1[time==0,V])
      print(paste0("Finding ex-ante WTP:", shawnames[shawnum],": ",policyname))
      wtp_wage[,eval(paste0("exante_",shawnames[shawnum],lumpname)):=1-(meanV/meanV1)^(1/(1-params$gamma))]
      
      shawnum<-shawnum+1
    }

  }
  if(basedata%in%c("meanstest","meanstestnoSSDI")){
    wtp_wage[,flow:=realflow] 
    wtp_wage[,realflow:=NULL]
  }

}

evalwtp<-function(paramvals,marriageprob, healthprob,
                  Wage, spWage,
                  marriageprob_init,
                  foodstamps, numkids, oecd,
                  shocks.wage, shocks.spwage,
                  wagepars, spwagepars,
                  select,selectC,
                  divorceshare=1,
                  onlysingle=FALSE,onlymarried=FALSE,onlyFT=0,workDI=0,earlyDI=0,evalasset=TRUE,
                  onlyapplicants=FALSE, jointtax = 1, nosave = 0, DI_meanstest = 0,
                  single_sameallowanceprob,onlySS=FALSE, onlymeanstest=FALSE, nowagevar=FALSE, 
                  nohealthcost = FALSE, noshaw=TRUE, noshaw_ib=TRUE,noshaw_iball=TRUE,
                  health_simpleprefs, single_sameprefs,
                  goldtol=1e-5,
                  filename){
  margin <- 1.1
  temp<-paramsetup(paramvals,wagepars,spwagepars, divorceshare=divorceshare, ptwork_halfcost=FALSE, single_sameallowanceprob=single_sameallowanceprob, health_simpleprefs=health_simpleprefs, single_sameprefs=single_sameprefs,goldsearch_tolerance = goldtol)
  params<-temp$params
  param_input<-temp$param_input
  rm(temp)
  
  if(nohealthcost==TRUE)  param_input[names(param_input)%in%
                                        c("theta_mod","theta_sev","eta_mod","eta_sev","speta_mod","F2","F3","F2_single","F3_single",
                                          "spF2")]<-0
  if(nowagevar==TRUE) params$wagevar<-matrix(0,2,2)
  
  
  #Estimate WTP as a reduction in earnings, or lump sum payment:
  wtp<-copy(simdata)
  wtp[,everApply:=max(Apply),by=i]
  wtp[,firstApply:=time==min(time*Apply+99999*(Apply==0)),by=i]
  if(onlyapplicants==TRUE){
    wtp<-wtp[everApply==1,]
  }
  
  wtp[,emp:=jobloss!=1]
  wtp[,spemp:=(2*(single==1))+(spjobloss!=1&single==0)]
  wtp[,row:=seq.int(nrow(wtp))]
  

  if(onlymeanstest==FALSE){
    params1<-params
    params1$SSgenerosity<-margin
    
    wtpfun(wtp,
           param_input,params1, workDI,earlyDI,jointtax, nosave, DI_meanstest,
           param_input,params, workDI,earlyDI,jointtax, nosave, DI_meanstest,
           marriageprob, healthprob,Wage,spWage,
           shocks.wage, shocks.spwage,marriageprob_init, 
           foodstamps, numkids, oecd,
           "SSgenerosity",paste("wtp_SSgenerosity",margin*100,sep="."),onlyFT,onlysingle,onlymarried,
           noshaw=noshaw,
           noshaw_ib=noshaw_ib,
           noshaw_iball=noshaw_iball,
           noSSDI1 = 0,
           filename=filename)
    for(meanstest in c(1)){
    wtpfun(wtp,
           param_input,params1, workDI,earlyDI,jointtax, nosave, meanstest,
           param_input,params, workDI,earlyDI,jointtax, nosave, meanstest,
           marriageprob, healthprob ,Wage,spWage,
           shocks.wage, shocks.spwage,marriageprob_init, 
           foodstamps, numkids, oecd,
           paste("SSgenerosity_meanstest",meanstest,sep="."),paste("wtp_SSgenerositymeanstest",meanstest,margin*100,sep="."),onlyFT,onlysingle,onlymarried,
           noshaw=noshaw,
           noshaw_ib=noshaw_ib,
           noshaw_iball=noshaw_iball,
           noSSDI1 = 0,
           basedata="meanstest",
           filename=filename)
    }
    wtpfun(wtp,
           param_input,params1, workDI,earlyDI,jointtax, nosave, 1,
           param_input,params, workDI,earlyDI,jointtax, nosave, 1,
           marriageprob, healthprob ,Wage,spWage,
           shocks.wage, shocks.spwage,marriageprob_init, 
           foodstamps, numkids, oecd,
           "SSgenerosity_meanstestnoSSDI",paste("wtp_SSgenerositymeanstestnoSSDI",margin*100,sep="."),onlyFT,onlysingle,onlymarried,
           noshaw=noshaw,
           noshaw_ib=noshaw_ib,
           noshaw_iball=noshaw_iball,
           noSSDI1 = 1,
           noSSDI0 = 1,
           basedata="meanstestnoSSDI",
           filename=filename)
    
  
  }
  
  if(onlySS==FALSE){
    if(onlymeanstest==FALSE){
      params1<-params
      params1$FSgenerosity<-margin
      
      wtpfun(wtp,
             param_input,params1, workDI,earlyDI,jointtax, nosave, DI_meanstest,
             param_input,params, workDI,earlyDI,jointtax, nosave, DI_meanstest,
             marriageprob, healthprob ,Wage,spWage,
             shocks.wage, shocks.spwage,marriageprob_init, 
             foodstamps, numkids, oecd,
             "FSgenerosity",paste("wtp_FSgenerosity",margin*100,sep="."),
             onlyFT,onlysingle,onlymarried,
             noshaw=noshaw,
             noshaw_ib=noshaw_ib,
             noshaw_iball=noshaw_iball,
             filename=filename)
      for(meanstest in c(1)){
        wtpfun(wtp,
             param_input,params1, workDI,earlyDI,jointtax, nosave, meanstest,
             param_input,params, workDI,earlyDI,jointtax, nosave, meanstest,
             marriageprob, healthprob ,Wage,spWage,
             shocks.wage, shocks.spwage,marriageprob_init, 
             foodstamps, numkids, oecd,
             paste("FSgenerosity_meanstest",meanstest,sep="."),paste("wtp_FSgenerositymeanstest",meanstest,margin*100,sep="."),
             onlyFT,onlysingle,onlymarried,
             noshaw=noshaw,
             noshaw_ib=noshaw_ib,
             noshaw_iball=noshaw_iball,
             noSSDI1 = 0,
             basedata="meanstest",
             filename=filename)
      }

    
    
      param_input1<-param_input
      param_input1[grepl("pi1.|pi2.|pi0.",names(param_input))]<-pmin(param_input1[grepl("pi1.|pi2.|pi0.",names(param_input))]*margin,1)
      
      wtpfun(wtp,
             param_input1,params, workDI,earlyDI,jointtax, nosave, DI_meanstest,
             param_input,params, workDI,earlyDI,jointtax, nosave, DI_meanstest,
             marriageprob, healthprob ,Wage,spWage,
             shocks.wage, shocks.spwage,marriageprob_init,
             foodstamps, numkids, oecd,
             "stringency",paste("wtp_stringency",margin*100,sep="."),
             onlyFT,onlysingle,onlymarried,
             noshaw=noshaw,
             noshaw_ib=noshaw_ib,
             noshaw_iball=noshaw_iball,
             filename=filename)
      for(meanstest in c(1)){
        wtpfun(wtp,
             param_input1,params, workDI,earlyDI,jointtax, nosave, meanstest,
             param_input,params, workDI,earlyDI,jointtax, nosave, meanstest,
             marriageprob, healthprob ,Wage,spWage,
             shocks.wage, shocks.spwage,marriageprob_init,
             foodstamps, numkids, oecd,
             paste("stringency_meanstest",meanstest,sep="."),paste("wtp_stringencymeanstest",meanstest,margin*100,sep="."),
             onlyFT,onlysingle,onlymarried,
             noshaw=noshaw,
             noshaw_ib=noshaw_ib,
             noshaw_iball=noshaw_iball,
             noSSDI1=0,
             basedata="meanstest",
             filename=filename)
      }


        param_input1<-param_input
        param_input1[grepl("pi1.|pi2.|pi0.",names(param_input)) & grepl("married",names(param_input))]<-pmin(param_input1[grepl("pi1.|pi2.|pi0.",names(param_input))  & grepl("married",names(param_input))]*margin,1)
        
        wtpfun(wtp,
               param_input1,params, workDI,earlyDI,jointtax, nosave, DI_meanstest,
               param_input,params, workDI,earlyDI,jointtax, nosave, DI_meanstest,
               marriageprob, healthprob ,Wage,spWage,
               shocks.wage, shocks.spwage,marriageprob_init,
               foodstamps, numkids, oecd,
               "marstringency",paste("wtp_marstringency",margin*100,sep="."),
               onlyFT,onlysingle,onlymarried,
               noshaw=noshaw,
               noshaw_ib=noshaw_ib,
               noshaw_iball=noshaw_iball,
               filename=filename)
        for(meanstest in c(1)){
          wtpfun(wtp,
                 param_input1,params, workDI,earlyDI,jointtax, nosave, meanstest,
                 param_input,params, workDI,earlyDI,jointtax, nosave, meanstest,
                 marriageprob, healthprob ,Wage,spWage,
                 shocks.wage, shocks.spwage,marriageprob_init,
                 foodstamps, numkids, oecd,
                 paste("marstringency_meanstest",meanstest,sep="."),paste("wtp_marstringencymeanstest",meanstest,margin*100,sep="."),
                 onlyFT,onlysingle,onlymarried,
                 noshaw=noshaw,
                 noshaw_ib=noshaw_ib,
                 noshaw_iball=noshaw_iball,
                 noSSDI1=0,
                 basedata="meanstest",
                 filename=filename)
        }
        

        param_input1<-param_input
        param_input1[grepl("pi1.|pi2.|pi0.",names(param_input)) & grepl("single",names(param_input))]<-pmin(param_input1[grepl("pi1.|pi2.|pi0.",names(param_input))  & grepl("single",names(param_input))]*margin,1)
        
        wtpfun(wtp,
               param_input1,params, workDI,earlyDI,jointtax, nosave, DI_meanstest,
               param_input,params, workDI,earlyDI,jointtax, nosave, DI_meanstest,
               marriageprob, healthprob ,Wage,spWage,
               shocks.wage, shocks.spwage,marriageprob_init,
               foodstamps, numkids, oecd,
               "singstringency",paste("wtp_singstringency",margin*100,sep="."),
               onlyFT,onlysingle,onlymarried,
               noshaw=noshaw,
               noshaw_ib=noshaw_ib,
               noshaw_iball=noshaw_iball,
               filename=filename)
        for(meanstest in c(1)){
          wtpfun(wtp,
                 param_input1,params, workDI,earlyDI,jointtax, nosave, meanstest,
                 param_input,params, workDI,earlyDI,jointtax, nosave, meanstest,
                 marriageprob, healthprob ,Wage,spWage,
                 shocks.wage, shocks.spwage,marriageprob_init,
                 foodstamps, numkids, oecd,
                 paste("singstringency_meanstest",meanstest,sep="."),paste("wtp_singstringencymeanstest",meanstest,margin*100,sep="."),
                 onlyFT,onlysingle,onlymarried,
                 noshaw=noshaw,
                 noshaw_ib=noshaw_ib,
                 noshaw_iball=noshaw_iball,
                 noSSDI1=0,
                 basedata="meanstest",
                 filename=filename)
        }

        
      
    }
    
    

            wtpfun(wtp,
               param_input,params, workDI,2,jointtax, nosave, DI_meanstest,
               param_input,params, workDI,earlyDI,jointtax, nosave, DI_meanstest,
               marriageprob, healthprob ,Wage,spWage,
               shocks.wage, shocks.spwage,marriageprob_init, 
               foodstamps, numkids, oecd,
               "EarlyDI","wtp_EarlyDI.110",onlyFT,onlysingle,onlymarried,
               noshaw=noshaw,
               noshaw_ib=noshaw_ib,
               noshaw_iball=noshaw_iball,
               filename=filename)

        
        for(meanstest in c(1)){
        wtpfun(wtp,
               param_input,params, workDI,2,jointtax, nosave, meanstest,
               param_input,params, workDI,earlyDI,jointtax, nosave, meanstest,
               marriageprob, healthprob ,Wage,spWage,
               shocks.wage, shocks.spwage,marriageprob_init, 
               foodstamps, numkids, oecd,
               paste("EarlyDI_meanstest",meanstest,sep="."),paste("wtp_EarlyDImeanstest",meanstest,"110",sep="."),onlyFT,onlysingle,onlymarried,
               noshaw=noshaw,
               noshaw_ib=noshaw_ib,
               noshaw_iball=noshaw_iball,
               noSSDI1 = 0,
               basedata="meanstest",
               filename=filename)

        }

        
        for(meanstest in c(1,20000,40000,90000)){
        wtpfun(wtp,
               param_input,params, workDI,earlyDI,jointtax, nosave, meanstest,
               param_input,params, workDI,earlyDI,jointtax, nosave, DI_meanstest,
               marriageprob, healthprob ,Wage,spWage,
               shocks.wage, shocks.spwage,marriageprob_init, 
               foodstamps, numkids, oecd,
               "MeansTest",paste("wtp_MeansTest",meanstest,"110",sep="."),onlyFT,onlysingle,onlymarried,
               noshaw=noshaw,
               noshaw_ib=noshaw_ib,
               noshaw_iball=noshaw_iball,
               filename=filename)
        }

        

      
  }
  return(wtp)
}


wtpfun_assetwage<-function(path,Vpath,wtp_wage,wtp_lump,param_input1,params1,marriageprob, healthprob,
                           Wage,spWage, shocks.wage, shocks.spwage, marriageprob_init,
                           policyname,lumpname,onlyFT,onlysingle,onlymarried,workDI,earlyDI,jointtax, nosave){
  origdir<-getwd()
  setwd(path)
  simdata1<-Valsim_solve(as.vector(param_input1),params1,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage), aperm(spWage),
                         shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                         marriageprob_init,numsims,lumpsum=0,print=1,onlyFT=onlyFT,onlysingle=onlysingle,onlymarried=onlymarried,
                         workDI=workDI,earlyDI=earlyDI,jointtax= jointtax, nosave = nosave)
  simdata1<-cleansim(simdata1,select,selectC)
  simdata1[,married:=1-single]
  simdata1[,initialmar:=max((age==min(age))*married),by=i]
  simdata1<-simdata1[order(initialmar,Type),]
  
  temp <-read.csv(paste0("V.csv"),header=FALSE)[,1:numtypes]
  V1<-array(NA,c(numtypes,50,dim(Wage)[3],dim(spWage)[3],dim(Asset)[3],2,3,3,3,2))
  V1<-aperm(V1)
  V1[,,,,,,,,,1]<-temp[,1]
  V1[,,,,,,,,,2]<-temp[,2]
  V1[,,,,,,,,,3]<-temp[,3]
  V1<-aperm(V1)
  rm(temp)
  
  setwd(origdir)
  temp <-read.csv(paste0(Vpath,"/V.csv"),header=FALSE)[,1:numtypes]
  V0<-array(NA,c(numtypes,50,dim(Wage)[3],dim(spWage)[3],dim(Asset)[3],2,3,3,3,2))
  V0<-aperm(V0)
  V0[,,,,,,,,,1]<-temp[,1]
  V0[,,,,,,,,,2]<-temp[,2]
  V0[,,,,,,,,,3]<-temp[,3]
  V0<-aperm(V0)
  rm(temp)
  
  print(paste0("Evaluating assets:",policyname))
  wtp_lump[,eval(lumpname):=Assetval_solve(V0,Type,time,i,wage,spwage,asset,DI,emp,spemp,Health,spHealth,V1,Wage,spWage,Asset,policyname),by=row]
  
  print(paste0("Evaluating wage:",policyname))
  wtp_wage[,eval(lumpname):=Wageval_solve(V0,Type,time,i,wage,spwage,asset,DI,emp,spemp,Health-1,spHealth-1,V1,Wage,spWage,Asset,policyname),by=row]
  print(paste0("Finding ex-ante WTP:",policyname))
  
  temp<-budgetbal(path, V0,  simdata, "noname", 0, "noname", param_input, params1, healthprob, marriageprob,foodstamps,numkids,oecd,
                  shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss,
                  shocks.marriage, marriageprob_init,numsims,
                  onlysingle=onlysingle,onlymarried=onlymarried,onlyFT=onlyFT, workDI=workDI, earlyDI=earlyDI,
                  jointtax= jointtax, nosave = nosave,
                  taxguess = 0, plotages = c(23,35,45,55), tablenames=TRUE, append=FALSE,
                  findbudget=FALSE, findwtp=TRUE,
                  newsimdata = simdata1, noplot = TRUE)
  wtp_wage[,eval(paste0("exante_",lumpname)):=temp$extra_tax]
}


evalwtp_assetwage<-function(path, Vpath, paramvals,marriageprob, healthprob,
                            Wage, spWage,
                            marriageprob_init,
                            shocks.wage, shocks.spwage,
                            wagepars, spwagepars,
                            select,selectC,
                            onlysingle=FALSE,onlymarried=FALSE,onlyFT=0,workDI=0,earlyDI=0,evalasset=TRUE,
                            onlyapplicants=FALSE, jointtax = 1, nosave = 0,
                            single_sameallowanceprob=TRUE,onlySS=FALSE, nowagevar=FALSE, nohealthcost = FALSE){
  
  temp<-paramsetup(paramvals,wagepars,spwagepars, ptwork_halfcost=FALSE, single_sameallowanceprob=single_sameallowanceprob)
  params<-temp$params
  param_input<-temp$param_input
  rm(temp)
  
  if(nohealthcost==TRUE)  param_input[names(param_input)%in%
                                        c("theta_mod","theta_sev","eta_mod","eta_sev","speta_mod","F2","F3","F2_single","F3_single",
                                          "spF2")]<-0
  if(nowagevar==TRUE) params$wagevar<-matrix(0,2,2)
  
  temp <-read.csv(paste0(Vpath ,"/V.csv"),header=FALSE)[,1:numtypes]
  V<-array(NA,c(numtypes,50,dim(Wage)[3],dim(spWage)[3],dim(Asset)[3],2,3,3,3,2))
  V<-aperm(V)
  V[,,,,,,,,,1]<-temp[,1]
  V[,,,,,,,,,2]<-temp[,2]
  V[,,,,,,,,,3]<-temp[,3]
  V<-aperm(V)
  rm(temp)
  
  wtp_asset<-data.table(type=rep(0:2,2), married=rep(0:1,each=3), t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0)
  wtp_asset[,spemp:=married+(1-married)*2]
  wtp_asset[,i:=.I]
  wtp_asset[,wage:=PermWage(t+23,wagepars,type+1),by=i] 
  wtp_asset[,spwage:=PermWage(t+23,spwagepars,type+1),by=i]
  wtp_asset[,wagepoint:=max(c(1,which(wage>Wage[type+1,t+1,-dim(Wage)[3]]))),by=i]
  wtp_asset[,spwagepoint:=max(c(1,which(spwage>spWage[type+1,t+1,-dim(spWage)[3]]))),by=i]
  wtp_asset[,assetpoint:=max(c(1,which(asset>Asset[type+1,t+1,-dim(Asset)[3]]))),by=i]
  wtp_asset[,wageinterp:= min((wage-Wage[type+1,t+1,wagepoint])/(Wage[type+1,t+1,wagepoint+1]-Wage[type+1,t+1,wagepoint]),1),by=i]
  if(dim(spWage)[3]>1) wtp_asset[,spwageinterp:= min((spwage-spWage[type+1,t+1,spwagepoint])/(spWage[type+1,t+1,spwagepoint+1]-spWage[type+1,t+1,spwagepoint]),1),by=i]
  else wtp_asset[,spwageinterp:=0]
  wtp_asset[,assetinterp:= min((asset-Asset[type+1,t+1,assetpoint])/(Asset[type+1,t+1,assetpoint+1]-Asset[type+1,t+1,assetpoint]),1),by=i]
  if(dim(spWage)[3]>1) {
    wtp_asset[,V_base:= wageinterp*spwageinterp*assetinterp*V[type+1,t+1,wagepoint+1,spwagepoint+1,assetpoint+1,emp+1,spemp+1,DI+1,health+1,sphealth+1]
              + (1-wageinterp)*spwageinterp*assetinterp*V[type+1,t+1,wagepoint,spwagepoint+1,assetpoint+1,emp+1,spemp+1,DI+1,health+1,sphealth+1]
              + wageinterp*(1-spwageinterp)*assetinterp*V[type+1,t+1,wagepoint+1,spwagepoint,assetpoint+1,emp+1,spemp+1,DI+1,health+1,sphealth+1]
              + wageinterp*spwageinterp*(1-assetinterp)*V[type+1,t+1,wagepoint+1,spwagepoint+1,assetpoint,emp+1,spemp+1,DI+1,health+1,sphealth+1]
              + (1-wageinterp)*(1-spwageinterp)*assetinterp*V[type+1,t+1,wagepoint,spwagepoint,assetpoint+1,emp+1,spemp+1,DI+1,health+1,sphealth+1]
              + (1-wageinterp)*spwageinterp*(1-assetinterp)*V[type+1,t+1,wagepoint,spwagepoint+1,assetpoint,emp+1,spemp+1,DI+1,health+1,sphealth+1]
              + wageinterp*(1-spwageinterp)*(1-assetinterp)*V[type+1,t+1,wagepoint+1,spwagepoint,assetpoint,emp+1,spemp+1,DI+1,health+1,sphealth+1]
              + (1-wageinterp)*(1-spwageinterp)*(1-assetinterp)*V[type+1,t+1,wagepoint,spwagepoint,assetpoint,emp+1,spemp+1,DI+1,health+1,sphealth+1],by=i]
  }
  else{
    wtp_asset[,V_base:= wageinterp*assetinterp*V[type+1,t+1,wagepoint+1,spwagepoint,assetpoint+1,emp+1,spemp+1,DI+1,health+1,sphealth+1]
              + (1-wageinterp)*assetinterp*V[type+1,t+1,wagepoint,spwagepoint,assetpoint+1,emp+1,spemp+1,DI+1,health+1,sphealth+1]
              + wageinterp*(1-assetinterp)*V[type+1,t+1,wagepoint+1,spwagepoint,assetpoint,emp+1,spemp+1,DI+1,health+1,sphealth+1]
              + (1-wageinterp)*(1-assetinterp)*V[type+1,t+1,wagepoint,spwagepoint,assetpoint,emp+1,spemp+1,DI+1,health+1,sphealth+1],by=i]
  }
  rm(V)
  #MAKE A POLICY COLUMN
  simdata[,married:=1-single]
  simdata[,initialmar:=max((age==min(age))*married),by=i]
  simdata<-simdata[order(initialmar,Type),]
  
  construct_wtp(wtp_asset,simdata,"baseline")
  
  if(evalasset==TRUE){
    #Finding budget-balanced reforms: 
    #1) First find the current budget. 
    #2) Then find the necessary increase in marginal tax rate to accompany the reform, to maintain same budget.
    #####This requires resimulating the model for different tax rates.
    #3) Evaluate changes in welfare across baseline vs. reformed models for person-years.
    temp<-copy(wtp_asset[policy=="baseline",])
    construct_wtp(temp,simdata,"SSstringency")
    param_input1<-param_input
    param_input1[grepl("pi1.|pi2.|pi0.",names(param_input))]<-pmin(param_input1[grepl("pi1.|pi2.|pi0.",names(param_input))]*1.1,1)
    temp[,wtp:= Policyval_solve(param_input1,params,healthprob,marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage),aperm(spWage),
                                V_base,type,wage,spwage,asset,married,t,emp,spemp,health,sphealth,DI,costtype=0,earlyDI=earlyDI,workDI=workDI,simdebug=0,policy_tolerance=1e-2,
                                onlysingle=onlysingle,onlymarried=onlymarried,onlyFT=onlyFT, jointtax = jointtax, nosave = nosave),by=i]
    wtp_asset<-rbind(wtp_asset,temp)
    
    temp<-copy(wtp_asset[policy=="baseline",])
    construct_wtp(temp,simdata,"SSgenerosity")
    
    params1<-params
    params1$SSgenerosity<-1.1
    temp[,wtp:= Policyval_solve(param_input,params1,healthprob,marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage),aperm(spWage),
                                V_base,type,wage,spwage,asset,married,t,emp,spemp,health,sphealth,DI,costtype=0,earlyDI=earlyDI,workDI=workDI,simdebug=0,policy_tolerance=1e-2,
                                onlysingle=onlysingle,onlymarried=onlymarried,onlyFT=onlyFT, jointtax = jointtax, nosave = nosave),by=i]
    wtp_asset<-rbind(wtp_asset,temp)
    
    temp<-copy(wtp_asset[policy=="baseline",])
    construct_wtp(temp,simdata,"FSgenerosity")
    
    params1<-params
    params1$FSgenerosity<-1.1
    temp[,wtp:= Policyval_solve(param_input,params1,healthprob,marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage),aperm(spWage),
                                V_base,type,wage,spwage,asset,married,t,emp,spemp,health,sphealth,DI,costtype=0,earlyDI=earlyDI,workDI=workDI,simdebug=0,policy_tolerance=1e-2,
                                onlysingle=onlysingle,onlymarried=onlymarried,onlyFT=onlyFT, jointtax = jointtax, nosave = nosave),by=i]
    wtp_asset<-rbind(wtp_asset,temp)
    
    
    tbl<-xtable(wtp_asset[,.(type,married,policy,wtp)],type="latex",digits=3)
    #align(tbl)<-"ll|ccc"
    print(tbl,file=paste0(path,"asset_medianWTP.tex"),tabular.environment='tabular',floating=FALSE,include.colnames=FALSE,include.rownames=FALSE)
  }
  
  
  
  #Estimate WTP as a reduction in earnings, or lump sum payment:
  wtp_lump<-copy(simdata)
  wtp_wage<-copy(simdata)
  if(onlyapplicants==TRUE){
    wtp_lump[,everApply:=max(Apply),by=i]
    wtp_wage[,everApply:=max(Apply),by=i]
    wtp_lump<-wtp_lump[everApply==1,]
    wtp_wage<-wtp_wage[everApply==1,]
  }
  wtp_lump[,emp:=jobloss!=1]
  wtp_lump[,spemp:=(2*(single==1))+(spjobloss!=1&single==0)]
  wtp_lump[,row:=seq.int(nrow(wtp_lump))]
  
  wtp_wage[,emp:=jobloss!=1]
  wtp_wage[,spemp:=(2*(single==1))+(spjobloss!=1&single==0)]
  wtp_wage[,row:=seq.int(nrow(wtp_wage))]
  
  setnames(wtp_lump,old=c("V","Wage","spWage","Asset"),new=c("v","wage","spwage","asset"))
  wtp_lump[,lowerasset:=min(Asset[Type,time+1,]),by=row]
  wtp_lump[,upperasset:=max(Asset[Type,time+1,]),by=row]
  #  wtp_lump<-wtp_lump[asset>=lowerasset&asset<=upperasset,]
  
  setnames(wtp_wage,old=c("V","Wage","spWage","Asset"),new=c("v","wage","spwage","asset"))
  
  for(margin in seq(from=0.6,to=1.4,by=0.1)){
    params1<-params
    params1$SSgenerosity<-margin
    
    wtpfun(path,Vpath,wtp_wage,wtp_lump,param_input,params1, marriageprob, healthprob ,Wage,spWage,
           shocks.wage, shocks.spwage,marriageprob_init,"SSgenerosity",paste("wtp_SSgenerosity",margin*100,sep="."),onlyFT,onlysingle,onlymarried,workDI,earlyDI,jointtax, nosave)
  }
  if(onlySS==FALSE){
    for(margin in seq(from=0.6,to=1.4,by=0.1)){
      params1<-params
      params1$FSgenerosity<-margin
      
      wtpfun(path,Vpath,wtp_wage,wtp_lump,param_input,params1, marriageprob, healthprob ,Wage,spWage,
             shocks.wage, shocks.spwage,marriageprob_init,"FSgenerosity",paste("wtp_FSgenerosity",margin*100,sep="."),onlyFT,onlysingle,onlymarried,workDI,earlyDI,jointtax, nosave)
    }
    
    
    for(margin in seq(from=0.6,to=1.4,by=0.1)){
      param_input1<-param_input
      param_input1[grepl("pi1.|pi2.|pi0.",names(param_input))]<-pmin(param_input1[grepl("pi1.|pi2.|pi0.",names(param_input))]*margin,1)
      
      wtpfun(path,Vpath,wtp_wage,wtp_lump,param_input1,params, marriageprob, healthprob ,Wage,spWage,
             shocks.wage, shocks.spwage,marriageprob_init,"stringency",paste("wtp_stringency",margin*100,sep="."),onlyFT,onlysingle,onlymarried,workDI,earlyDI,jointtax, nosave)
    }
    
    wtpfun(path,Vpath,wtp_wage,wtp_lump,param_input,params, marriageprob, healthprob ,Wage,spWage,
           shocks.wage, shocks.spwage,marriageprob_init,"WorkApply","wtp_WorkApply.100",onlyFT,onlysingle,onlymarried,workDI=1,earlyDI=earlyDI,jointtax, nosave)
    wtpfun(path,Vpath,wtp_wage,wtp_lump,param_input,params, marriageprob, healthprob ,Wage,spWage,
           shocks.wage, shocks.spwage, marriageprob_init,"WorkDI","wtp_WorkDI.100",onlyFT,onlysingle,onlymarried,workDI=2,earlyDI=earlyDI,jointtax, nosave)
    
    wtpfun(path,Vpath,wtp_wage,wtp_lump,param_input,params, marriageprob, healthprob ,Wage,spWage,
           shocks.wage, shocks.spwage,marriageprob_init,"EarlyDI","wtp_EarlyDI.100",onlyFT,onlysingle,onlymarried,workDI,earlyDI=2,jointtax, nosave)
    
    for(margin in seq(from=0.6,to=1.4,by=0.1)){
      if(margin != 1) {
        wtp_wage[,eval(paste("wtp_WorkApply",margin*100,sep=".")):=NA]
        wtp_lump[,eval(paste("wtp_WorkApply",margin*100,sep=".")):=NA]
        wtp_wage[,eval(paste("exante_wtp_WorkApply",margin*100,sep=".")):=NA]
        wtp_lump[,eval(paste("exante_wtp_WorkApply",margin*100,sep=".")):=NA]
        
        wtp_wage[,eval(paste("wtp_WorkDI",margin*100,sep=".")):=NA]
        wtp_lump[,eval(paste("wtp_WorkDI",margin*100,sep=".")):=NA]
        wtp_wage[,eval(paste("exante_wtp_WorkDI",margin*100,sep=".")):=NA]
        wtp_lump[,eval(paste("exante_wtp_WorkDI",margin*100,sep=".")):=NA]
        
        wtp_wage[,eval(paste("wtp_EarlyDI",margin*100,sep=".")):=NA]
        wtp_lump[,eval(paste("wtp_EarlyDI",margin*100,sep=".")):=NA]
        wtp_wage[,eval(paste("exante_wtp_EarlyDI",margin*100,sep=".")):=NA]
        wtp_lump[,eval(paste("exante_wtp_EarlyDI",margin*100,sep=".")):=NA]
        
      }
    }
  }
  # for(policyname in levels(as.factor(wtp_wage$policy))){
  #   wtp_wage[policy==policyname,Work_healthydiff := Work_healthy-wtp_wage[policy=="baseline",Work_healthy]]
  #   wtp_wage[policy==policyname,Work_sickdiff := Work_sick-wtp_wage[policy=="baseline",Work_sick]]
  #   wtp_wage[policy==policyname,Work_vsickdiff := Work_vsick-wtp_wage[policy=="baseline",Work_vsick]]
  #   wtp_wage[policy==policyname,spWork_healthydiff := spWork_healthy-wtp_wage[policy=="baseline",spWork_healthy]]
  #   wtp_wage[policy==policyname,spWork_sickdiff := spWork_sick-wtp_wage[policy=="baseline",spWork_sick]]
  #   wtp_wage[policy==policyname,spWork_vsickdiff := spWork_vsick-wtp_wage[policy=="baseline",spWork_vsick]]
  #   wtp_wage[policy==policyname,DI_healthydiff := DI_healthy-wtp_wage[policy=="baseline",DI_healthy]]
  #   wtp_wage[policy==policyname,DI_sickdiff := DI_sick-wtp_wage[policy=="baseline",DI_sick]]
  #   wtp_wage[policy==policyname,DI_vsickdiff := DI_vsick-wtp_wage[policy=="baseline",DI_vsick]]
  # }
  # 
  # wtp_wage<-rbind(wtp_wage,
  #                 data.table(type=NA, policy="SSgenerosity", married=0, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[married==0&policy=="SSgenerosity",wtp]%*%simdata[age==min(age)&initialmar==0,sum(!is.na(age)),by=Type]$V1/nrow(simdata[age==min(age)&initialmar==0,]))),
  #                 data.table(type=NA, policy="FSgenerosity", married=0, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[married==0&policy=="FSgenerosity",wtp]%*%simdata[age==min(age)&initialmar==0,sum(!is.na(age)),by=Type]$V1/nrow(simdata[age==min(age)&initialmar==0,]))),
  #                 data.table(type=NA, policy="stringency", married=0, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[married==0&policy=="stringency",wtp]%*%simdata[age==min(age)&initialmar==0,sum(!is.na(age)),by=Type]$V1/nrow(simdata[age==min(age)&initialmar==0,]))),
  #                 data.table(type=NA, policy="Workapply", married=0, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[married==0&policy=="Workapply",wtp]%*%simdata[age==min(age)&initialmar==0,sum(!is.na(age)),by=Type]$V1/nrow(simdata[age==min(age)&initialmar==0,]))),
  #                 data.table(type=NA, policy="WorkDI", married=0, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[married==0&policy=="WorkDI",wtp]%*%simdata[age==min(age)&initialmar==0,sum(!is.na(age)),by=Type]$V1/nrow(simdata[age==min(age)&initialmar==0,]))),
  #                 data.table(type=NA, policy="EarlyDI", married=0, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[married==0&policy=="EarlyDI",wtp]%*%simdata[age==min(age)&initialmar==0,sum(!is.na(age)),by=Type]$V1/nrow(simdata[age==min(age)&initialmar==0,]))
  #                 ),
  #                 data.table(type=NA, policy="SSgenerosity", married=1, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[married==1&policy=="SSgenerosity",wtp]%*%simdata[age==min(age)&initialmar==1,sum(!is.na(age)),by=Type]$V1/nrow(simdata[age==min(age)&initialmar==1,]))),
  #                 data.table(type=NA, policy="FSgenerosity", married=1, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[married==1&policy=="FSgenerosity",wtp]%*%simdata[age==min(age)&initialmar==1,sum(!is.na(age)),by=Type]$V1/nrow(simdata[age==min(age)&initialmar==1,]))),
  #                 data.table(type=NA, policy="stringency", married=1, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[married==1&policy=="stringency",wtp]%*%simdata[age==min(age)&initialmar==1,sum(!is.na(age)),by=Type]$V1/nrow(simdata[age==min(age)&initialmar==1,]))),
  #                 data.table(type=NA, policy="Workapply", married=1, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[married==1&policy=="Workapply",wtp]%*%simdata[age==min(age)&initialmar==1,sum(!is.na(age)),by=Type]$V1/nrow(simdata[age==min(age)&initialmar==1,]))),
  #                 data.table(type=NA, policy="WorkDI", married=1, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[married==1&policy=="WorkDI",wtp]%*%simdata[age==min(age)&initialmar==1,sum(!is.na(age)),by=Type]$V1/nrow(simdata[age==min(age)&initialmar==1,]))),
  #                 data.table(type=NA, policy="EarlyDI", married=1, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[married==1&policy=="EarlyDI",wtp]%*%simdata[age==min(age)&initialmar==1,sum(!is.na(age)),by=Type]$V1/nrow(simdata[age==min(age)&initialmar==1,]))
  #                 ),
  #                 data.table(type=0, policy="SSgenerosity", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==0&policy=="SSgenerosity",wtp]%*%simdata[age==min(age)&Type==1,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==1,]))),
  #                 data.table(type=0, policy="FSgenerosity", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==0&policy=="FSgenerosity",wtp]%*%simdata[age==min(age)&Type==1,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==1,]))),
  #                 data.table(type=0, policy="stringency", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==0&policy=="stringency",wtp]%*%simdata[age==min(age)&Type==1,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==1,]))),
  #                 data.table(type=0, policy="Workapply", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==0&policy=="Workapply",wtp]%*%simdata[age==min(age)&Type==1,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==1,]))),
  #                 data.table(type=0, policy="WorkDI", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==0&policy=="WorkDI",wtp]%*%simdata[age==min(age)&Type==1,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==1,]))),
  #                 data.table(type=0, policy="EarlyDI", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==0&policy=="EarlyDI",wtp]%*%simdata[age==min(age)&Type==1,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==1,]))
  #                 ),
  #                 data.table(type=1, policy="SSgenerosity", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==1&policy=="SSgenerosity",wtp]%*%simdata[age==min(age)&Type==2,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==2,]))),
  #                 data.table(type=1, policy="FSgenerosity", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==1&policy=="FSgenerosity",wtp]%*%simdata[age==min(age)&Type==2,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==2,]))),
  #                 data.table(type=1, policy="stringency", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==1&policy=="stringency",wtp]%*%simdata[age==min(age)&Type==2,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==2,]))),
  #                 data.table(type=1, policy="Workapply", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==1&policy=="Workapply",wtp]%*%simdata[age==min(age)&Type==2,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==2,]))),
  #                 data.table(type=1, policy="WorkDI", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==1&policy=="WorkDI",wtp]%*%simdata[age==min(age)&Type==2,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==2,]))),
  #                 data.table(type=1, policy="EarlyDI", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==1&policy=="EarlyDI",wtp]%*%simdata[age==min(age)&Type==2,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==2,]))
  #                 ),
  #                 data.table(type=2, policy="SSgenerosity", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==2&policy=="SSgenerosity",wtp]%*%simdata[age==min(age)&Type==3,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==3,]))),
  #                 data.table(type=2, policy="FSgenerosity", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==2&policy=="FSgenerosity",wtp]%*%simdata[age==min(age)&Type==3,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==3,]))),
  #                 data.table(type=2, policy="stringency", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==2&policy=="stringency",wtp]%*%simdata[age==min(age)&Type==3,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==3,]))),
  #                 data.table(type=2, policy="Workapply", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==2&policy=="Workapply",wtp]%*%simdata[age==min(age)&Type==3,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==3,]))),
  #                 data.table(type=2, policy="WorkDI", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==2&policy=="WorkDI",wtp]%*%simdata[age==min(age)&Type==3,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==3,]))),
  #                 data.table(type=2, policy="EarlyDI", married=NA, t = 0,DI=0,asset=0,emp=1,health=0,sphealth=0,
  #                            wtp = as.vector(wtp_wage[type==2&policy=="EarlyDI",wtp]%*%simdata[age==min(age)&Type==3,sum(!is.na(age)),by=married]$V1/nrow(simdata[age==min(age)&Type==3,]))
  #                 ),fill=TRUE
  #                 
  # )
  # wtp_wage[is.na(type),type:=99]
  # wtp_wage[is.na(married),married:=99]
  # wtp_wagewide<-reshape(data=wtp_wage[,.(type,married,policy,wtp)],v.names="wtp",timevar="policy",idvar=c("type","married"), direction="wide")
  # tbl<-xtable(wtp_wagewide[,.(type,married,wtp.stringency,wtp.SSgenerosity,wtp.FSgenerosity,
  #                             wtp.Workapply,wtp.WorkDI,wtp.EarlyDI)],type="latex",digits=3)
  # #align(tbl)<-"lll|cccccc"
  # colnames(tbl)<-c("Type","Married","DI Stringency","DI Generosity","Food Stamp Generosity","Work While Applying", "Work on DI","Temporary DI")
  # print(tbl,file=paste0(path,"wage_medianWTP.tex"),only.contents=TRUE,floating=FALSE,include.colnames=TRUE,include.rownames=FALSE,hline.after=NULL)
  # 
  # tbl<-xtable(wtp_wage[,.(type,married,policy,Work_vsickdiff, spWork_vsickdiff,DI_vsickdiff,
  #                         Work_sickdiff, spWork_sickdiff,DI_sickdiff,
  #                         Work_healthydiff, spWork_healthydiff, DI_healthydiff)],type="latex",digits=3)
  # #align(tbl)<-"lll|ccc|ccc|ccc"
  # colnames(tbl)<-c("Type","Married","Policy","Work","Partn. Work","DI","Work","Partn. Work","DI","Work","Partn. Work","DI")
  # print(tbl,file=paste0(path,"wage_policies.tex"),only.contents=TRUE,floating=FALSE,include.colnames=TRUE,include.rownames=FALSE,hline.after=NULL)
  # 
  return(list(lump=wtp_lump,wage=wtp_wage))
}

#Reporting comparison of baseline and counterfactual WTP for reforms
wtpchange<-function(wtp_original,wtp_cfact,Type,marital,path,wtpname){
  wtpcols<-names(wtp_cfact)[grepl("wtp_",names(wtp_cfact))]
  for(var in wtpcols){
    wtp_original[is.infinite(get(var)),eval(var):=NA]
  }
  outdata<-(wtp_cfact[time==0,lapply(.SD,mean, na.rm=TRUE),.SDcols=wtpcols])
  names(outdata)[str_count(names(outdata),"\\.")==2]<-sub("\\.","__",names(outdata)[str_count(names(outdata),"\\.")==2])
  outdata<-reshape(outdata,direction="long",varying=names(outdata),sep=".")
  outdata[,dataset:="Counterfactual"]
  names(outdata)<-sub("__","\\.",names(outdata))
  
  wtpcols<-names(wtp_original)[grepl("wtp_",names(wtp_original))]
  for(var in wtpcols){
    wtp_original[is.infinite(get(var)),eval(var):=NA]
  }
  origdata<-(wtp_original[time==0,lapply(.SD,mean, na.rm=TRUE),.SDcols=wtpcols])
  names(origdata)[str_count(names(origdata),"\\.")==2]<-sub("\\.","__",names(origdata)[str_count(names(origdata),"\\.")==2])
  origdata<-reshape(origdata,direction="long",varying=names(origdata),sep=".")
  origdata[,dataset:="Baseline"]
  names(origdata)<-sub("__","\\.",names(origdata))
  
  outdata<-rbind(outdata,origdata,fill=TRUE)
  
  outdata[,id:=NULL]
  setnames(outdata,"time","margin")
  summary_origcompare<-outdata
  summary_origcompare[,counterfactual:=wtpname]
  
  summary_marcompare<-data.table()
  summary_typecompare<-data.table()
  summary_martypecompare<-data.table()
  
  
  wtpcols<-names(wtp_cfact)[grepl("wtp_",names(wtp_cfact))]
  
  #Making type and initmar-specific WTP
  outdata<-(wtp_cfact[order(single,Type),][time==0,lapply(.SD,mean, na.rm=TRUE),.SDcols=c(wtpcols),by=.(single,Type)]) #[,lapply(.SD,diff),.SDcols=wtpcols])
  names(outdata)[str_count(names(outdata),"\\.")==2]<-sub("\\.","__",names(outdata)[str_count(names(outdata),"\\.")==2])
  outdata<-reshape(outdata,direction="long",idvar=c("single","Type"),varying=names(outdata)[!names(outdata)%in%c("single","Type")],sep=".")
  outdata[,dataset:="Counterfactual"]
  names(outdata)<-sub("__","\\.",names(outdata))
  origdata<-(wtp_original[order(single,Type),][time==0,lapply(.SD,mean, na.rm=TRUE),.SDcols=c(wtpcols),by=.(single,Type)]) #[,lapply(.SD,diff),.SDcols=wtpcols])
  names(origdata)[str_count(names(origdata),"\\.")==2]<-sub("\\.","__",names(origdata)[str_count(names(origdata),"\\.")==2])
  origdata<-reshape(origdata,direction="long",idvar=c("single","Type"),varying=names(origdata)[!names(origdata)%in%c("single","Type")],sep=".")
  origdata[,dataset:="Baseline"]
  names(origdata)<-sub("__","\\.",names(origdata))
  
  outdata<-rbind(outdata,origdata)
  outdata[,id:=NULL]
  setnames(outdata,"time","margin")
  
  summary_martypecompare<-outdata
  summary_martypecompare[,counterfactual:=wtpname]
  
  if(Type==TRUE){
    #Taking the difference across types in willingness to pay measures
    outdata<-(wtp_cfact[order(Type),][time==0,lapply(.SD,mean, na.rm=TRUE),.SDcols=c(wtpcols,"Type"),by=Type])
    names(outdata)[str_count(names(outdata),"\\.")==2]<-sub("\\.","__",names(outdata)[str_count(names(outdata),"\\.")==2])
    outdata<-reshape(outdata,direction="long",idvar="Type",varying=names(outdata)[names(outdata)!="Type"],sep=".")
    outdata[,dataset:="Counterfactual"]
    names(outdata)<-sub("__","\\.",names(outdata))
    origdata<-(wtp_original[order(Type),][time==0,lapply(.SD,mean, na.rm=TRUE),.SDcols=c(wtpcols,"Type"),by=Type])
    names(origdata)[str_count(names(origdata),"\\.")==2]<-sub("\\.","__",names(origdata)[str_count(names(origdata),"\\.")==2])
    origdata<-reshape(origdata,direction="long",idvar="Type",varying=names(origdata)[names(origdata)!="Type"],sep=".")
    origdata[,dataset:="Baseline"]
    names(origdata)<-sub("__","\\.",names(origdata))
    
    outdata<-rbind(outdata,origdata)
    outdata[,id:=NULL]
    setnames(outdata,"time","margin")
    
    summary_typecompare<-outdata
    summary_typecompare[,counterfactual:=wtpname]
    
    
    
    
  }
  if(marital==TRUE){
    outdata<-(wtp_cfact[order(single),][time==0,lapply(.SD,mean, na.rm=TRUE),.SDcols=c(wtpcols),by=single]) #[,lapply(.SD,diff),.SDcols=wtpcols])
    names(outdata)[str_count(names(outdata),"\\.")==2]<-sub("\\.","__",names(outdata)[str_count(names(outdata),"\\.")==2])
    outdata<-reshape(outdata,direction="long",idvar="single",varying=names(outdata)[names(outdata)!="single"],sep=".")
    outdata[,dataset:="Counterfactual"]
    names(outdata)<-sub("__","\\.",names(outdata))
    origdata<-(wtp_original[order(single),][time==0,lapply(.SD,mean, na.rm=TRUE),.SDcols=c(wtpcols),by=single]) #[,lapply(.SD,diff),.SDcols=wtpcols])
    names(origdata)[str_count(names(origdata),"\\.")==2]<-sub("\\.","__",names(origdata)[str_count(names(origdata),"\\.")==2])
    origdata<-reshape(origdata,direction="long",idvar="single",varying=names(origdata)[names(origdata)!="single"],sep=".")
    origdata[,dataset:="Baseline"]
    names(origdata)<-sub("__","\\.",names(origdata))
    
    outdata<-rbind(outdata,origdata)
    outdata[,id:=NULL]
    setnames(outdata,"time","margin")
    
    summary_marcompare<-outdata
    summary_marcompare[,counterfactual:=wtpname]
    
    
    
  }
  #for ALL reforms, printing a table of the difference in WTP, with each reform as a column.
  #will combine this across counterfactual specifications, where each one is a row.
  #So define a variable to keep track of the counterfactual.
  #NOTE: for behavioral effects, use budgetbal() code.
  return( list(summary_origcompare=summary_origcompare,
               summary_marcompare=summary_marcompare,
               summary_typecompare=summary_typecompare,
               summary_martypecompare=summary_martypecompare))
} 



plotwtp<-function(wtp_lump,plotname, wtpquants= c(0.1,0.25,0.5,0.75,0.9), wtpages=c(35,45,55)){
  for(var in c(names(wtp_lump)[grepl("wtp_",names(wtp_lump)) & ! (grepl("single",names(wtp_lump))|grepl("married",names(wtp_lump)))],"asset")){
    
    if(var != "asset") {
      plotlab <- "Lump Sum Willingness to Pay"
    }
    else {
      plotlab <- "Accumulated Savings"
    }
    
    for(a in wtpages){
      for(d in c(1,2)){
        for(h in levels(as.factor(wtp_lump$Health))){
          for(sph in levels(as.factor(wtp_lump$spHealth))){
            pdf(paste0("./figures/wtp/",plotname, var,"_distage",a,"_h",h,"_sph",sph,"_DI",d,'.pdf'))
            print(ggplot(data=wtp_lump[Health==h & spHealth==sph & DI == d & age == a & ! is.infinite(get(var)),],
                         aes(x=get(var),group=interaction(Type,single)))
                  +geom_density(aes(color=as.factor(Type), linetype = as.factor(single)),size=1.5)
                  +geom_vline(xintercept=0,linetype="dashed")
                  +scale_linetype_manual(values=c("solid","dotted"),labels=c("Married","Single"))
                  +labs(linetype="Marital Status",color="Household Type",
                        y="Density",
                        x=plotlab)
                  
            )
            dev.off()
          }
        }
      }
    }
    for(prob in wtpquants){
      
      assetdist<-wtp_lump[jobloss==0 & spjobloss == 0 ,
                          .(value=quantile(get(var),probs=prob,na.rm=TRUE)),by=.(Type,age,DI,Health,spHealth,single)]
      for(d in c(1,2)){
        for(h in levels(as.factor(assetdist$Health))){
          for(sph in levels(as.factor(assetdist$spHealth))){
            pdf(paste0("./figures/wtp/",plotname, var,"_byage_p",prob*100,"_h",h,"_sph",sph,"_DI",d,'.pdf'))
            print(ggplot(data=assetdist[Health==h & spHealth==sph & DI == d,],
                         aes(x=age,y=value,group=interaction(Type,single)))
                  +geom_line(aes(color=as.factor(Type)),size=1.5)
                  +geom_point(data=assetdist[Health==h & spHealth==sph & DI == d & age%%2==0,],
                              aes(shape=as.factor(single)))
                  +geom_hline(yintercept=0,linetype="dashed")
                  +scale_shape_manual(values=c(16,0),labels=c("Married","Single"))
                  +labs(shape="Marital Status",color="Household Type",
                        x="Age",
                        y=plotlab)
                  
            )
            dev.off()
          }
        }
      }
    }
    assetmean<-wtp_lump[jobloss==0 & spjobloss == 0 & !is.infinite(get(var)),
                        .(value=mean(get(var),na.rm=TRUE)),by=.(Type,age,DI,Health,spHealth,single)]
    for(d in c(1,2)){
      for(h in levels(as.factor(assetmean$Health))){
        for(sph in levels(as.factor(assetmean$spHealth))){
          pdf(paste0("./figures/wtp/",plotname, var,"_byage_mean","_h",h,"_sph",sph,"_DI",d,'.pdf'))
          print(ggplot(data=assetmean[Health==h & spHealth==sph & DI == d,],
                       aes(x=age,y=value,group=interaction(Type,single)))
                +geom_line(aes(color=as.factor(Type)),size=1.5)
                +geom_point(data=assetmean[Health==h & spHealth==sph & DI == d & age%%2==0,],
                            aes(shape=as.factor(single)))
                +geom_hline(yintercept=0,linetype="dashed")
                +scale_shape_manual(values=c(16,0),labels=c("Married","Single"))
                +labs(shape="Marital Status",color="Household Type",
                      x="Age",
                      y=plotlab)
          )
          dev.off()
        }
      }
    }
    if(var!="asset"){
      for(prob in wtpquants){
        assetdist<-wtp_lump[jobloss==0 & spjobloss == 0 ,
                            .(value_married=quantile(get(paste0(var,"_married")),probs=prob,na.rm=TRUE),
                              value_single=quantile(get(paste0(var,"_single")),probs=prob,na.rm=TRUE)),by=.(Type,age,DI,Health,spHealth)]
        
        for(d in c(1,2)){
          for(h in levels(as.factor(assetdist$Health))){
            for(sph in levels(as.factor(assetdist$spHealth))){
              pdf(paste0("./figures/wtp/",plotname, var,"_fixasset_byage_p",prob*100,"_h",h,"_sph",sph,"_DI",d,'.pdf'))
              print(ggplot(data=assetdist[Health==h & spHealth==sph & DI == d,],
                           aes(x=age,group=Type))
                    +geom_line(aes(y=value_married, color=as.factor(Type)),size=1.5)
                    +geom_line(aes(y=value_single, color=as.factor(Type)),size=1.5)
                    +geom_point(data=assetdist[Health==h & spHealth==sph & DI == d & age%%2==0,],
                                aes(y=value_married, shape="Married"))
                    +geom_point(data=assetdist[Health==h & spHealth==sph & DI == d & age%%2==0,],
                                aes(y=value_single, shape="Single"))
                    +scale_shape_manual(values=c(16,0),labels=c("Married","Single"))
                    +geom_hline(yintercept=0,linetype="dashed")
                    +labs(color="Household Type",
                          x="Age",
                          y="Lump Sum Willingness to Pay")
                    
              )
              dev.off()
            }
          }
        }
      }
      assetmean<-wtp_lump[jobloss==0 & spjobloss == 0 & ! is.infinite(paste0(var,"_married")),
                          .(value_married=mean(get(paste0(var,"_married")),na.rm=TRUE)),by=.(Type,age,DI,Health,spHealth)]
      assetmean1<-wtp_lump[jobloss==0 & spjobloss == 0 & ! is.infinite(paste0(var,"_married")),
                           .(value_single=mean(get(paste0(var,"_single")),na.rm=TRUE)),by=.(Type,age,DI,Health,spHealth)]
      assetmean <- merge(assetmean,assetmean1,by=c("Type","age","DI","Health","spHealth"),all=TRUE)
      for(d in c(1,2)){
        for(h in levels(as.factor(assetmean$Health))){
          for(sph in levels(as.factor(assetmean$spHealth))){
            pdf(paste0("./figures/wtp/", plotname, var,"_fixasset_byage_mean","_h",h,"_sph",sph,"_DI",d,'.pdf'))
            print(ggplot(data=assetmean[Health==h & spHealth==sph & DI == d,],
                         aes(x=age,group=Type))
                  +geom_line(aes(y=value_married, color=as.factor(Type)),size=1.5)
                  +geom_line(aes(y=value_single, color=as.factor(Type)),size=1.5)
                  +geom_point(data=assetmean[Health==h & spHealth==sph & DI == d & age%%2==0,],
                              aes(y=value_married, shape="Married"))
                  +geom_point(data=assetmean[Health==h & spHealth==sph & DI == d & age%%2==0,],
                              aes(y=value_single, shape="Single"))
                  +geom_hline(yintercept=0,linetype="dashed")
                  +scale_shape_manual(values=c(16,0),labels=c("Married","Single"))
                  +labs(shape="Marital Status",color="Household Type",
                        x="Age",
                        y="Lump Sum Willingness to Pay")
            )
            
            dev.off()
          }
        }
      }
    }
    
    
  }
}


####### WTP CODE DONE ######




############ Budget-balanced reforms and their effect on welfare ###############


#need to output an object with the proportional change in V, applications, DI rolls, gross output
budgetbal<-function(path, V0, simdata, reformname, margin, plotname, param_input, params, healthprob, marriageprob,foodstamps,numkids,oecd,
                    shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss,
                    shocks.marriage, marriageprob_init,numsims,
                    onlysingle, onlymarried, onlyFT, workDI=0, earlyDI=0, noSSDI = 0,
                    jointtax= 1, nosave = 0, DI_meanstest = 0,
                    budget_tol=1e-5, taxguess = 0, plotages = c(23,35,45,55), tablenames=FALSE, append=TRUE,
                    findbudget= TRUE, findbudget_allowance=FALSE, findbudget_generosity=FALSE,
                    findbudget_meanstest=FALSE, #A mix of a wage tax and means test
                    findwtp= FALSE, newsimdata=NULL, noplot=TRUE) {
  
  if(findbudget==TRUE | findbudget_allowance==TRUE | findbudget_generosity==TRUE | findbudget_meanstest == TRUE) budget<-simdata[,sum(NetTax/(params$R^time))] - simdata[,sum(Transfers/(params$R^time))] - simdata[,sum(reassessed/(params$R^time))]*params$cost_reassess
  if(findwtp ==TRUE) budget<- -simdata[time==0,mean(V)]
  #Solving value functions with reform:
  origpath<-getwd()
  setwd(path)
  
  if(is.null(newsimdata)) newsimdata<-as.data.table(Valsim_solve(as.vector(param_input),params,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage), aperm(spWage),
                                                                 shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                                                                 marriageprob_init,numsims,lumpsum=0,print=1,
                                                                 onlysingle=onlysingle,onlymarried=onlymarried,onlyFT=onlyFT,workDI=workDI,earlyDI=earlyDI,
                                                                 jointtax= jointtax, nosave = nosave, noSSDI =noSSDI, DI_meanstest=DI_meanstest))
  
  simdata1<-copy(newsimdata)
  if(findbudget==TRUE  | findbudget_allowance==TRUE | findbudget_generosity==TRUE | findbudget_meanstest == TRUE) budget1<-simdata1[,sum(NetTax/(params$R^time))] - simdata1[,sum(Transfers/(params$R^time))] - simdata1[,sum(reassessed/(params$R^time))]*params$cost_reassess
  if(findwtp ==TRUE) budget1<- -simdata1[time==0,mean(V)]
  
  # temp <-read.csv(paste0("V.csv"),header=FALSE)[,1:numtypes]
  # V1<-array(NA,c(numtypes,50,dim(Wage)[3],dim(spWage)[3],dim(Asset)[3],2,3,3,3,2))
  # V1<-aperm(V1)
  # V1[,,,,,,,,,1]<-temp[,1]
  # V1[,,,,,,,,,2]<-temp[,2]
  # V1[,,,,,,,,,3]<-temp[,3]
  # V1<-aperm(V1)
  extra_tax<-0

  
  #If reform with no extra taxis is budget neutral, we're done. Else:
  print(paste("Original budgets:",budget,budget1))
  if(!is.infinite(extra_tax) & (abs(budget-budget1) > budget_tol*(abs(budget1)+abs(budget)))){
    #Defining function to easily resimulate from those value functions:
    budget_resim<- function(extra_tax,findbudget_allowance, findbudget_generosity, findbudget_meanstest){
      
      param_inputtemp<-param_input
      paramstemp<-params
      newmeanstest <- DI_meanstest
      
      if(findbudget_allowance==FALSE & findbudget_generosity==FALSE & findbudget_meanstest == FALSE){
        paramstemp<-params
        paramstemp$ficataxmult <-(params$ficataxmult+extra_tax)
      }
      if(findbudget_meanstest==TRUE){
        newmeanstest <- extra_tax
      }
      if(findbudget_allowance==TRUE) {
        param_inputtemp[grepl("pi1.|pi2.|pi0.",names(param_inputtemp))]<-param_inputtemp[grepl("pi1.|pi2.|pi0.",names(param_inputtemp))]*(1-extra_tax)
        param_inputtemp[grepl("pi1.|pi2.|pi0.",names(param_inputtemp))]<-pmax(param_inputtemp[grepl("pi1.|pi2.|pi0.",names(param_inputtemp))],0)
        param_inputtemp[grepl("pi1.|pi2.|pi0.",names(param_inputtemp))]<-pmin(param_inputtemp[grepl("pi1.|pi2.|pi0.",names(param_inputtemp))],1)
      }
      if(findbudget_generosity==TRUE) {
        paramstemp$SSgenerosity<-paramstemp$SSgenerosity-extra_tax
      }
      
      sim<-as.data.table(Valsim_solve(as.vector(param_inputtemp),paramstemp,healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage), aperm(spWage),
                                      shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                                      marriageprob_init,numsims,lumpsum=0,print=0,
                                      onlysingle=onlysingle,onlymarried=onlymarried,onlyFT=onlyFT,workDI=workDI,earlyDI=earlyDI,
                                      jointtax= jointtax, nosave = nosave, noSSDI = noSSDI, DI_meanstest = newmeanstest))
      return(sim)
    }
    
    #For means test, first check if we can get budget surplus with most aggressive 
    #test possible (which happens with extra_tax --> 0)
    if(findbudget_meanstest == TRUE) taxguess <- 0.1
    extra_tax <- taxguess
    lowertax <- taxguess
    #Resimulate takes as its arguments the choice-specific value functions and a wage tax.
    #It spits out a new simulated dataset accounting for effects of tax on behaviors
    simdata1<-budget_resim(taxguess,findbudget_allowance,findbudget_generosity, findbudget_meanstest)
    
    if(findbudget==TRUE | findbudget_allowance==TRUE | findbudget_generosity == TRUE | findbudget_meanstest== TRUE) budget1<-simdata1[,sum(NetTax/(params$R^time))] - simdata1[,sum(Transfers/(params$R^time))] - simdata1[,sum(reassessed/(params$R^time))]*params$cost_reassess
    if(findwtp ==TRUE) budget1<- -simdata1[time==0,mean(V)]
    
    #If we still have a budget deficit with fully binding means test, 
    #then a means test cannot implement the reform
    
    print(paste("Budgets with initial lowertax:",budget,budget1))
    
    if(findbudget_meanstest==TRUE & budget1 < budget) {
      extra_tax<- -Inf
    } 
    else { 
      if(findbudget_meanstest==TRUE){
      uppertax <- 0.1
      lowertax <- max(newsimdata$Asset)
    }
    while(budget1 > budget){
      if(findbudget_allowance==TRUE|findbudget_generosity==TRUE) lowertax <-(lowertax-0.1)
      else if(findbudget_meanstest == TRUE) lowertax <- lowertax*2
      else lowertax <- (lowertax -0.01)
      simdata1<-budget_resim( extra_tax = lowertax,findbudget_allowance,findbudget_generosity, findbudget_meanstest)
      if(findbudget==TRUE | findbudget_allowance==TRUE | findbudget_generosity == TRUE | findbudget_meanstest == TRUE) budget1<-simdata1[,sum(NetTax/(params$R^time))] - simdata1[,sum(Transfers/(params$R^time))] - simdata1[,sum(reassessed/(params$R^time))]*params$cost_reassess
      if(findwtp ==TRUE) budget1<- -simdata1[time==0,mean(V)]
      print(paste0("Finding lower bound on price, p=",lowertax," budget surplus:",budget1-budget))
      if(findbudget_allowance==TRUE & lowertax < 1-max(1/param_input[grepl("pi1.|pi2.|pi0.",names(param_input)) & param_input!=0]) & budget1 > budget) {
        extra_tax<- -999
        break 
      }
    }
    if( findbudget_meanstest == FALSE){  
      uppertax <- 0.05

    simdata1<-budget_resim( extra_tax = uppertax,findbudget_allowance, findbudget_generosity, findbudget_meanstest)
    if(findbudget==TRUE | findbudget_allowance==TRUE | findbudget_generosity == TRUE | findbudget_meanstest == TRUE) budget1<-simdata1[,sum(NetTax/(params$R^time))] - simdata1[,sum(Transfers/(params$R^time))] - simdata1[,sum(reassessed/(params$R^time))]*params$cost_reassess
    if(findwtp ==TRUE) budget1<- -simdata1[time==0,mean(V)]

    print(paste("Budgets with initial uppertax:",budget,budget1))
    
    while(budget1 < budget) {
      uppertax <- 2 * uppertax 
      simdata1<-budget_resim( extra_tax = uppertax,findbudget_allowance, findbudget_generosity, findbudget_meanstest)
      if(findbudget==TRUE| findbudget_allowance==TRUE | findbudget_generosity == TRUE | findbudget_meanstest == TRUE) budget1<-simdata1[,sum(NetTax/(params$R^time))] - simdata1[,sum(Transfers/(params$R^time))] - simdata1[,sum(reassessed/(params$R^time))]*params$cost_reassess
      if(findwtp ==TRUE) budget1<- -simdata1[time==0,mean(V)]
      print(paste0("Finding upper bound on price, p=",uppertax," budget surplus:",budget1-budget))
      if(findbudget_allowance==TRUE & uppertax > 1 & budget1 < budget) {
        extra_tax<- 999
        break 
      }
    }
    }
    
    while(abs(budget - budget1)>budget_tol*(abs(budget)+abs(budget1))) {
      if(extra_tax==-999 | extra_tax ==999 | is.infinite(extra_tax)) break
      extra_tax <- (uppertax+lowertax)/2
      simdata1<-budget_resim( extra_tax = extra_tax,findbudget_allowance, findbudget_generosity, findbudget_meanstest)
      if(findbudget==TRUE | findbudget_allowance==TRUE | findbudget_generosity == TRUE) budget1<-simdata1[,sum(NetTax/(params$R^time))] - simdata1[,sum(Transfers/(params$R^time))] - simdata1[,sum(reassessed/(params$R^time))]*params$cost_reassess
      if(findwtp ==TRUE) budget1<- -simdata1[time==0,mean(V)]
      
      if(budget1 > budget) uppertax<-extra_tax
      if(budget1 < budget) lowertax<-extra_tax
      print(paste0("Finding solution, guess = ",extra_tax," budget surplus:",budget1-budget))
      if(findbudget_allowance==TRUE & extra_tax > 1 & budget1 < budget) {
        extra_tax<- 999
        break 
      }
      if(findbudget_allowance==TRUE & extra_tax < 1-max(1/param_input[grepl("pi1.|pi2.|pi0.",names(param_input)) & param_input!=0]) & budget1 > budget) {
        extra_tax<- -999
        break 
      }
      
    }
    }
  }
  
  ############ Budget-balanced reforms and their effect on welfare ###############
  setwd(origpath)
  
  #mapping tax change into a percent value:
  if(findbudget_meanstest == FALSE) extra_tax<-extra_tax*100
  
  #for budget balance reform, include the tax in behavioral effects
  #for ex-ante WTP, just look at the effects of the reform without tax changes
  
  if(findwtp==TRUE) simdata1<-newsimdata
  #cleaning up the simdata1 file if it wasn't brought in cleaned:
  if(is.null(simdata1$yearDI))simdata1<-cleansim(simdata1,select,selectC)
  
  #finding moral hazard pre- and post-reform
  simdata[,MoralHazard:=Wage*exp(wagepars$wagereg[[Type]]$health[[Health]])*params$hours*moralhazard(Ceq,Work,spWork,single,Health,spHealth,Wage*params$hours,spWage*params$hours,time,ageold,yearDI,Apply,numkids,Type,param_input),by=row]
  simdata1[,MoralHazard:=Wage*exp(wagepars$wagereg[[Type]]$health[[Health]])*params$hours*moralhazard(Ceq,Work,spWork,single,Health,spHealth,Wage*params$hours,spWage*params$hours,time,ageold,yearDI,Apply,numkids,Type,param_input),by=row]
  
  print(paste("Merging baseline and counterfactual simulations..."))
  
  simdata1 <- merge(simdata[,.(i,time,C,V,GrossOutput,Wage,spWage,Asset,jobloss,Transfers, spjobloss, DI, Apply, yearDI, Work,spWork,MoralHazard, VonDI, NetTax, RejectedLast, TransfersifDI)],simdata1,by=c("i","time"),all=TRUE, suffixes=c("_orig",""))
  print("Merge complete.")
  meanflow<-abs(simdata[age <= 62,mean(flow(Ceq,Work,spWork,single,Health,spHealth,param_input))])
  simdata1<-simdata1[order(single,Type),]
  
  setorder(simdata1,i,-time)
  simdata1[,futureC_orig := cumsum(C_orig/(params$R^time)),by=i]
  setorder(simdata1,i,time)
  

  
  budgetbal_summary<-data.table()
  for(byg in c("neither","single","Type","both")){
    print(paste("making summaray table:",byg))
    if(byg=="neither") bygroups<-""
    else if(byg=="both")bygroups<-c("single","Type")
    else bygroups<-byg
    budgbal_sum <- cbind(reform=reformname,
                         margin=margin,
                         extra_tax=extra_tax,
                         proportional_change_V=simdata1[time==0,mean(V-V_orig)/abs(mean(V_orig)),by=eval(bygroups)]$V1,
                         level_change_V=simdata1[time==0,mean(V-V_orig)*100/meanflow,by=eval(bygroups)]$V1,
                         WTP=simdata1[time==0,1-(mean(V_orig)/mean(V))^(1/(1-params$gamma)),by=eval(bygroups)]$V1*100,
                         WTP_Cons=simdata1[time==0,1-(mean(V_orig)/mean(V))^(1/(1-params$gamma)),by=eval(bygroups)]$V1*(
                           simdata1[,mean(C/(params$R^time)),by=eval(bygroups)]$V1
                         ),
                         share_rejected=simdata1[, mean(RejectedLast_orig)],
                         wtp_getDI =  simdata1[,mean((RejectedLast_orig==1)*
                                                       (1-(V_orig/VonDI_orig)^(1/(1-params$gamma)))*
                                                       futureC_orig)/1000],
                         level_cons_orig = simdata1[,mean(C/(params$R^time)),by=eval(bygroups)]$V1/1000,
                         level_change_NetTax = simdata1[,mean(NetTax/(params$R^time)-NetTax_orig/(params$R^time))/1000],
                         level_change_Transfers = simdata1[,mean(Transfers/(params$R^time)-Transfers_orig/(params$R^time))/1000],
                         level_stockDI_orig = simdata1[,mean(yearDI_orig)*100],
                         level_DIbenefits_orig = simdata1[,mean(Transfers * yearDI_orig)/1000],
                         level_ApplicantBenefits_orig = simdata1[,mean(Apply_orig*TransfersifDI_orig)/1000],
                         level_stockApply_orig = simdata1[,mean(Apply_orig)*100],
                         simdata1[age <= 62, .(proportional_change_Output=sum(GrossOutput/(params$R^time)-GrossOutput_orig/(params$R^time))/sum(GrossOutput_orig/(params$R^time)),
                                               level_change_Output=mean(GrossOutput/(params$R^time)-GrossOutput_orig/(params$R^time))/1000,
                                               proportional_change_Apply=sum(Apply-Apply_orig)/sum(Apply_orig),
                                               level_change_Apply=mean(Apply-Apply_orig)*100,
                                               proportional_change_Rolls=sum(yearDI-yearDI_orig)/sum(yearDI_orig),
                                               level_change_Rolls=mean(yearDI-yearDI_orig)*100,
                                               proportional_change_Work=sum(Work-Work_orig)/sum(Work_orig),
                                               level_change_Work=mean(Work-Work_orig)*100,
                                               proportional_change_spWork=sum(spWork-spWork_orig)/sum(spWork_orig),
                                               level_change_spWork=mean(spWork-spWork_orig)*100,
                                               proportional_change_MoralHazard=(sum(MoralHazard/(params$R^time),na.rm=TRUE)-sum(MoralHazard_orig/(params$R^time),na.rm=TRUE))/sum(MoralHazard_orig/(params$R^time),na.rm=TRUE),
                                               level_change_MoralHazard=(mean(MoralHazard/(params$R^time),na.rm=TRUE)-mean(MoralHazard_orig/(params$R^time),na.rm=TRUE)),
                                               N=.N),by=eval(bygroups)],
                         simdata1[age <= 62 & Health==1, .(proportional_change_Output_H1=sum(GrossOutput-GrossOutput_orig)/sum(GrossOutput_orig),
                                                           level_change_Output_H1=mean(GrossOutput-GrossOutput_orig)/1000,
                                                           proportional_change_Apply_H1=sum(Apply-Apply_orig)/sum(Apply_orig),
                                                           level_change_Apply_H1=mean(Apply-Apply_orig)*100,
                                                           proportional_change_Rolls_H1=sum(yearDI-yearDI_orig)/sum(yearDI_orig),
                                                           level_change_Rolls_H1=mean(yearDI-yearDI_orig)*100,
                                                           proportional_change_Work_H1=sum(Work-Work_orig)/sum(Work_orig),
                                                           level_change_Work_H1=mean(Work-Work_orig)*100,
                                                           proportional_change_spWork=sum(spWork-spWork_orig)/sum(spWork_orig),
                                                           level_change_spWork=mean(spWork-spWork_orig)*100,
                                                           proportional_change_MoralHazard_H1=(sum(MoralHazard/(params$R^time),na.rm=TRUE)-sum(MoralHazard_orig/(params$R^time),na.rm=TRUE))/sum(MoralHazard_orig/(params$R^time),na.rm=TRUE),
                                                           level_change_MoralHazard_H1=(mean(MoralHazard/(params$R^time),na.rm=TRUE)-mean(MoralHazard_orig/(params$R^time),na.rm=TRUE)),
                                                           N_H1=.N),by=eval(bygroups)][,-c("Type","single"),with=FALSE],
                         simdata1[age <= 62 & Health==2, .(proportional_change_Output_H2=sum(GrossOutput-GrossOutput_orig)/sum(GrossOutput_orig),
                                                           level_change_Output_H2=mean(GrossOutput-GrossOutput_orig)/1000,
                                                           proportional_change_Apply_H2=sum(Apply-Apply_orig)/sum(Apply_orig),
                                                           level_change_Apply_H2=mean(Apply-Apply_orig)*100,
                                                           proportional_change_Rolls_H2=sum(yearDI-yearDI_orig)/sum(yearDI_orig),
                                                           level_change_Rolls_H2=mean(yearDI-yearDI_orig)*100,
                                                           proportional_change_Work_H2=sum(Work-Work_orig)/sum(Work_orig),
                                                           level_change_Work_H2=mean(Work-Work_orig)*100,
                                                           proportional_change_spWork=sum(spWork-spWork_orig)/sum(spWork_orig),
                                                           level_change_spWork=mean(spWork-spWork_orig)*100,
                                                           proportional_change_MoralHazard_H2=(sum(MoralHazard/(params$R^time),na.rm=TRUE)-sum(MoralHazard_orig/(params$R^time),na.rm=TRUE))/sum(MoralHazard_orig/(params$R^time),na.rm=TRUE),
                                                           level_change_MoralHazard_H2=(mean(MoralHazard/(params$R^time),na.rm=TRUE)-mean(MoralHazard_orig/(params$R^time),na.rm=TRUE)),
                                                           N_H2=.N),by=eval(bygroups)][,-c("Type","single"),with=FALSE],
                         simdata1[age <= 62 & Health==3, .(proportional_change_Output_H3=sum(GrossOutput-GrossOutput_orig)/sum(GrossOutput_orig),
                                                           level_change_Output_H3=mean(GrossOutput-GrossOutput_orig)/1000,
                                                           proportional_change_Apply_H3=sum(Apply-Apply_orig)/sum(Apply_orig),
                                                           level_change_Apply_H3=mean(Apply-Apply_orig)*100,
                                                           proportional_change_Rolls_H3=sum(yearDI-yearDI_orig)/sum(yearDI_orig),
                                                           level_change_Rolls_H3=mean(yearDI-yearDI_orig)*100,
                                                           proportional_change_Work_H3=sum(Work-Work_orig)/sum(Work_orig),
                                                           level_change_Work_H3=mean(Work-Work_orig)*100,
                                                           proportional_change_spWork=sum(spWork-spWork_orig)/sum(spWork_orig),
                                                           level_change_spWork=mean(spWork-spWork_orig)*100,
                                                           proportional_change_MoralHazard_H3=(sum(MoralHazard/(params$R^time),na.rm=TRUE)-sum(MoralHazard_orig/(params$R^time),na.rm=TRUE))/sum(MoralHazard_orig/(params$R^time),na.rm=TRUE),
                                                           level_change_MoralHazard_H3=(mean(MoralHazard/(params$R^time),na.rm=TRUE)-mean(MoralHazard_orig/(params$R^time),na.rm=TRUE)),
                                                           N_H3=.N),by=eval(bygroups)][,-c("Type","single"),with=FALSE])
    
    if(byg=="neither"){
      budgbal_sum[,Type:=999]
      budgbal_sum[,single:=999]
    }
    if(byg=="single") budgbal_sum[,Type:=999]
    if(byg=="Type") budgbal_sum[,single:=999]
    
    budgetbal_summary<-rbind(budgetbal_summary,budgbal_sum)
  }
  
  
  return(list(simdata=simdata1,extra_tax=extra_tax, budgetbal_summary=budgetbal_summary))
  
} 



####### Budget-balanced reforms done #############

###CONSEQUENCES OF REFORMS WHICH LEAD TO X% DROP IN DI ROLLS####
paramadjust<-function(reformname,adjust,params,param_input){
  params1<-params
  param_input1<-param_input
  if(reformname=="DI Generosity (%)") params1$SSgenerosity<-params$SSgenerosity*adjust
  if(reformname=="DI Stringency (%)") {
    param_input1[grepl("pi1.|pi2.|pi0.",names(param_input))]<-pmax(pmin(param_input1[grepl("pi1.|pi2.|pi0.",names(param_input))]*(adjust),1),0)
  }
  return(list(params=params1,param_input=param_input1))
}
rollreduce<-function(path, rollchange = 0.1, reducetype="rolls", V0, simdata, reformname, plotname, param_input, params, healthprob, marriageprob,foodstamps,numkids,oecd,
                     shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss,
                     shocks.marriage, marriageprob_init,numsims,
                     onlysingle, onlymarried, onlyFT, workDI=0, earlyDI=0,
                     roll_tol=2.5e-3, plotages = c(23,35,45,55), tablenames=FALSE, append=TRUE) {
  
  if(reducetype=="roll"){
    Rolls<-simdata[,sum(yearDI)]
    Rolls_target<-simdata[,sum(yearDI)]*(1-rollchange)
  }
  if(reducetype=="fiscal"){
    Rolls<-simdata[yearDI==1,sum(Transfers)]
    Rolls_target<-simdata[yearDI==1,sum(Transfers)]*(1-rollchange)
  }
  #Solving value functions with reform:
  
  #Defining function to easily resimulate with new parameters:
  roll_resim<- function(reformname, adjust, params, param_input){
    sim<-Valsim_solve(as.vector(paramadjust(reformname, adjust, params, param_input)$param_input),
                      paramadjust(reformname, adjust, params, param_input)$params,
                      healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage), aperm(spWage),
                      shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                      marriageprob_init,numsims,lumpsum=0,print=0,workDI=0,onlyFT=1)
    sim<-cleansim(sim,select=select,selectC=selectC)
    
    return(sim)
  }
  
  adjust <- 0.5
  adjustlow <- 0
  adjusthigh<- 1
  #Resimulate takes as its arguments the choice-specific value functions and a wage tax.
  #It spits out a new simulated dataset accounting for effects of tax on behaviors
  
  while(abs(Rolls-Rolls_target) > roll_tol*(abs(Rolls)+abs(Rolls_target))) {
    print(paste("Current and target  numbers are:", Rolls,"and",Rolls_target))
    print(paste("From adjust", adjust))
    adjust <- (adjusthigh+adjustlow)/2
    simdata1<-roll_resim(reformname, adjust, params, param_input)
    if(reducetype=="roll"){
      Rolls<- simdata1[,sum(yearDI)]
    }
    if(reducetype=="fiscal"){
      Rolls<-simdata1[yearDI==1,sum(Transfers)]
    }  
    
    if(Rolls > Rolls_target) adjusthigh<-adjust
    if(Rolls < Rolls_target) adjustlow<-adjust
  }
  
  ##Simulating one more time, to print value matrices.
  simdata1<-Valsim_solve(as.vector(paramadjust(reformname, adjust, params, param_input)$param_input),
                         paramadjust(reformname, adjust, params, param_input)$params,
                         healthprob, marriageprob,foodstamps,numkids,oecd,aperm(Asset),aperm(Wage), aperm(spWage),
                         shocks.wage,shocks.spwage,shocks.health,shocks.allow,shocks.reassess,shocks.jobloss,shocks.spjobloss, shocks.marriage,
                         marriageprob_init,numsims,lumpsum=0,print=1,workDI=0,onlyFT=1)
  simdata1<-cleansim(simdata1,select=select,selectC=selectC)
  
  meanflow<-abs(simdata[age <= 62,mean(flow(Ceq,Work,spWork,single,Health,spHealth,param_input))])
  
  simdata1 <- merge(simdata[,.(i,time,V,GrossOutput,Wage,spWage,Asset,jobloss, spjobloss, DI, Apply, yearDI)],simdata1,by=c("i","time"),all=TRUE, suffixes=c("_orig",""))
  
  
  simdata1<-simdata1[order(single,Type),]
  roll_summary<-data.table()
  for(byg in c("neither","single","Type","both")){
    if(byg=="neither") bygroups<-""
    else if(byg=="both")bygroups<-c("single","Type")
    else bygroups<-byg
    
    roll_sum <- cbind(reform=reformname,
                      adjustment=adjust,
                      proportional_change_V=simdata1[time==0,mean(V-V_orig)/abs(mean(V_orig)),by=eval(bygroups)]$V1,
                      level_change_V=simdata1[time==0,mean(V-V_orig)*100/meanflow,by=eval(bygroups)]$V1,
                      simdata1[age <= 62, .(proportional_change_Output=sum(GrossOutput-GrossOutput_orig)/sum(GrossOutput_orig),
                                            level_change_Output=mean(GrossOutput-GrossOutput_orig)/1000,
                                            proportional_change_Apply=sum(Apply-Apply_orig)/sum(Apply_orig),
                                            level_change_Apply=mean(Apply-Apply_orig)*100,
                                            proportional_change_Rolls=sum(yearDI-yearDI_orig)/sum(yearDI_orig),
                                            level_change_Rolls=mean(yearDI-yearDI_orig)*100,
                                            N=.N),by=eval(bygroups)],
                      simdata1[age <= 62 & Health==1, .(proportional_change_Output_H1=sum(GrossOutput-GrossOutput_orig)/sum(GrossOutput_orig),
                                                        level_change_Output_H1=mean(GrossOutput-GrossOutput_orig)/1000,
                                                        proportional_change_Apply_H1=sum(Apply-Apply_orig)/sum(Apply_orig),
                                                        level_change_Apply_H1=mean(Apply-Apply_orig)*100,
                                                        proportional_change_Rolls_H1=sum(yearDI-yearDI_orig)/sum(yearDI_orig),
                                                        level_change_Rolls_H1=mean(yearDI-yearDI_orig)*100,
                                                        N_H1=.N),
                               by=eval(bygroups)][,-c("Type","single"),with=FALSE],
                      simdata1[age <= 62 & Health==2, .(proportional_change_Output_H2=sum(GrossOutput-GrossOutput_orig)/sum(GrossOutput_orig),
                                                        level_change_Output_H2=mean(GrossOutput-GrossOutput_orig)/1000,
                                                        proportional_change_Apply_H2=sum(Apply-Apply_orig)/sum(Apply_orig),
                                                        level_change_Apply_H2=mean(Apply-Apply_orig)*100,
                                                        proportional_change_Rolls_H2=sum(yearDI-yearDI_orig)/sum(yearDI_orig),
                                                        level_change_Rolls_H2=mean(yearDI-yearDI_orig)*100,
                                                        N_H2=.N),by=eval(bygroups)][,-c("Type","single"),with=FALSE],
                      simdata1[age <= 62 & Health==3, .(proportional_change_Output_H3=sum(GrossOutput-GrossOutput_orig)/sum(GrossOutput_orig),
                                                        level_change_Output_H3=mean(GrossOutput-GrossOutput_orig)/1000,
                                                        proportional_change_Apply_H3=sum(Apply-Apply_orig)/sum(Apply_orig),
                                                        level_change_Apply_H3=mean(Apply-Apply_orig)*100,
                                                        proportional_change_Rolls_H3=sum(yearDI-yearDI_orig)/sum(yearDI_orig),
                                                        level_change_Rolls_H3=mean(yearDI-yearDI_orig)*100,
                                                        N_H3=.N),by=eval(bygroups)][,-c("Type","single"),with=FALSE])
    
    if(byg=="neither"){
      roll_sum[,Type:=NA]
      roll_sum[,single:=NA]
    }
    if(byg=="single") roll_sum[,Type:=NA]
    if(byg=="Type") roll_sum[,single:=NA]
    
    roll_summary<-rbind(roll_summary,roll_sum)
  }
  
  
  roll_summary[,single:=as.character(single)]
  roll_summary[single=="0",single:="Married"]
  roll_summary[single=="1",single:="Single"]
  roll_summary<-as.data.table(roll_summary)
  setcolorder(roll_summary,c("reform","Type","single","adjustment","proportional_change_V","level_change_V",
                             "proportional_change_Output","level_change_Output","proportional_change_Apply",
                             "level_change_Apply","proportional_change_Rolls","level_change_Rolls"))
  
  tbl_prop<-xtable(roll_summary[,c("Type","single","adjustment","proportional_change_V",
                                   "proportional_change_Output","proportional_change_Apply",
                                   "proportional_change_Rolls"),with=FALSE],
                   type="latex",digits=3)
  tbl_level<-xtable(roll_summary[,c("Type","single","adjustment","level_change_V",
                                    "level_change_Output","level_change_Apply",
                                    "level_change_Rolls"),with=FALSE],
                    type="latex",digits=3)
  
  colnames(tbl_prop)<-c("Type","Marital Status","Adjustment","Welfare","Output",
                        "Applications", "DI Rolls")
  print(tbl_prop,file=paste0(path,plotname,"_",reducetype,"_effects_proportional.tex"),tabular.environment='tabular',floating=FALSE,include.colnames=TRUE,include.rownames=FALSE)
  
  colnames(tbl_level)<-c("Type","Marital Status","Adjustment","Welfare","Output",
                         "Applications", "Rolls")
  print(tbl_level,file=paste0(path,plotname,"_",reducetype,"_effects_level.tex"),tabular.environment='tabular',floating=FALSE,include.colnames=TRUE,include.rownames=FALSE)
  
  
  #examine willingness to pay for budget-balanced policy:
  #V0 is the value function from baseline simulations
  #V1 is value function from budget-balanced reform
  #Estimate WTP as a reduction in earnings, or lump sum payment:
  simdata1[,emp:=jobloss_orig!=1]
  simdata1[,spemp:=(2*(single==1))+(spjobloss_orig!=1&single==0)]
  simdata1[,row:=seq.int(nrow(simdata1))]
  simdata1[,lowerasset:=min(get("Asset",globalenv())[Type,time+1,]),by=row]
  simdata1[,upperasset:=max(get("Asset",globalenv())[Type,time+1,]),by=row]
  
  
  temp <-read.csv(paste0("V.csv"),header=FALSE)[,1:numtypes]
  V1<-array(NA,c(numtypes,50,dim(Wage)[3],dim(spWage)[3],dim(Asset)[3],2,3,3,3,2))
  V1<-aperm(V1)
  V1[,,,,,,,,,1]<-temp[,1]
  V1[,,,,,,,,,2]<-temp[,2]
  V1[,,,,,,,,,3]<-temp[,3]
  V1<-aperm(V1)
  
  simdata1[,wtp_rollbal:=Assetval_solve(V0,Type,time,i,Wage_orig,spWage_orig,Asset_orig,DI_orig,emp,spemp,Health,spHealth,V1,
                                        get("Wage",globalenv()),get("spWage",globalenv()),get("Asset",globalenv()),plotname),by=row]
  #examine distribution of V-V_orig by observables, at fixed ages
  for(a in plotages){
    
    for(trim in c(0.01,0.05,0.10,0.20)){
      for(var in c("V","Asset","GrossOutput")){
        varquants<-quantile(simdata1[age==a,(get(var)-get(paste0(var,"_orig")))/abs(get(paste0(var,"_orig")))],probs=c(trim,1-trim),na.rm=TRUE)
        pdf(paste0(path,plotname,"_",reducetype,"_", var,"_distage",a,'_trim',trim,'.pdf'))
        print(ggplot(data=simdata1[age==a,],
                     aes(x=(get(var)-get(paste0(var,"_orig")))/abs(get(paste0(var,"_orig"))),
                         group=interaction(Type,single)))
              +geom_density(aes(color=as.factor(Type), linetype=as.factor(single)), size=1.5)
              +geom_vline(xintercept=0,linetype="dashed")
              +xlim(c(varquants[1],varquants[2]))
              +scale_linetype_manual(values=c("solid","dotted"),labels=c("Married","Single"))
              +labs(linetype="Marital Status",color="Household Type",
                    y="Density",
                    x=paste0("Proportional Change in ",var))
              +theme(legend.position="bottom",legend.box="vertical")
              
        )
        
        print(ggplot(data=simdata1[age==a,],
                     aes(x=(get(var)-get(paste0(var,"_orig"))),
                         group=interaction(Type,single)))
              +geom_density(aes(color=as.factor(Type), linetype=as.factor(single)), size=1.5)
              +geom_vline(xintercept=0,linetype="dashed")
              +xlim(c(varquants[1],varquants[2]))
              +scale_linetype_manual(values=c("solid","dotted"),labels=c("Married","Single"))
              +labs(linetype="Marital Status",color="Household Type",
                    y="Density",
                    x=paste0("Change in ",var))
              +theme(legend.position="bottom",legend.box="vertical")
              
        )
        
        
        print(ggplot(data=simdata1[age==a,],
                     aes(y=(get(var)-get(paste0(var,"_orig"))),
                         x = get(paste0(var,"_orig")),
                         group=interaction(Type,single)))
              +geom_smooth(aes(color=as.factor(Type), linetype=as.factor(single)), size=1.5)
              +geom_vline(xintercept=0,linetype="dashed")
              +xlim(c(varquants[1],varquants[2]))
              +scale_linetype_manual(values=c("solid","dotted"),labels=c("Married","Single"))
              +labs(linetype="Marital Status",color="Household Type",
                    x=var,
                    y=paste0("Change in ",var))
              +theme(legend.position="bottom",legend.box="vertical")
              
        )
        dev.off()
        
      }
      wtpquants<-quantile(simdata1[ age == a & ! is.infinite(wtp_rollbal),wtp_rollbal],probs=c(trim,1-trim))
      pdf(paste0(path,"/wtp/",plotname,"_",reducetype,"_wtp_distage",a,'_trim',trim,'.pdf'))
      print(ggplot(data=simdata1[ age == a & ! is.infinite(wtp_rollbal),],
                   aes(x=wtp_rollbal,group=interaction(Type,single)))
            +geom_density(aes(color=as.factor(Type), linetype = as.factor(single)),size=1.5)
            +xlim(c(min(wtpquants[1],0),max(0,wtpquants[2])))
            +geom_vline(xintercept=0,linetype="dashed")
            +scale_linetype_manual(values=c("solid","dotted"),labels=c("Married","Single"))
            +labs(linetype="Marital Status",color="Household Type",
                  y="Density",
                  x="Lump Sum Willingness to Pay")
            +theme(legend.position="bottom",legend.box="vertical")
            
      )
      
      wtpquants<-quantile(simdata1[ age == a & ! is.infinite(wtp_rollbal),wtp_rollbal/Asset_orig],probs=c(trim,1-trim), na.rm=TRUE)
      print(ggplot(data=simdata1[ age == a & ! is.infinite(wtp_rollbal),],
                   aes(x=wtp_rollbal/Asset_orig,group=interaction(Type,single)))
            +geom_density(aes(color=as.factor(Type), linetype = as.factor(single)),size=1.5)
            +geom_vline(xintercept=0,linetype="dashed")
            +scale_linetype_manual(values=c("solid","dotted"),labels=c("Married","Single"))
            +xlim(c(min(0,wtpquants[1]),max(0,wtpquants[2])))
            +labs(linetype="Marital Status",color="Household Type",
                  y="Density",
                  x="Willingness to Pay as a Proportion of Assets")
            +theme(legend.position="bottom",legend.box="vertical")
            
            
      )
      dev.off()
    }
    
  }
  
  
  return(list(simdata=simdata1,adjustment=adjust, roll_summary=roll_summary))
  
} 

########### ROLL-DECREASING REFORMS DONE ######



cleansim<-function(simdata,select,selectC){
  simdata<-as.data.table(simdata)
  simdata[,Health:=Health+1]
  simdata[,spHealth:=spHealth+1]
  
  print(simdata[C<=0])
  simdata[,row:=1:nrow(simdata)]
  simdata[,Ceq:=C/oecd[[Type+1]][time+1,single+1],by=row]
  simdata[,age:=floor(time/params$agelength+23)]
  simdata[,ageold:=age>=45*params$agelength]
  simdata[,yearcons:=sum(Ceq),by=.(age,i,Type)]
  simdata[,yearDI:=DI==2 & age<=62*params$agelength]
  
  simdata[,select:=select]
  simdata[,selectC:=selectC]
  simdata[select==1,enterDI:=yearDI==1&c(NA,yearDI[-.N])==0&time<62*params$agelength,by=i]
  simdata[select==1,LastDI:=c(NA,yearDI[-.N])==1&time<62*params$agelength,by=i]
  simdata[,ApplyLast:=c(NA,Apply[-.N]),by=i]
  simdata[,RejectedLast:=c(0,Rejected[-.N]),by=i]
  simdata[,HealthLast:=c(NA,Health[-.N]),by=i]
  simdata[select==1&yearDI==1&enterDI!=1,enterDI:=NA]
  simdata[,Type:=Type+1]
}
